You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现指定字典转换?禁用列表、元组、append方法

正确实现方案

你之前的错误是把处理对象搞反了——误将原字典的值'hello'拆成字符作为新键,而实际需求是把原字典的键'name'拆成每个字符作为新键,值保留'hello'。

方法一:字典推导式(简洁实现)

D = {'name': 'hello'}
result = {char: D['name'] for char in next(iter(D))}
  • 说明:next(iter(D))直接获取原字典的唯一键'name'(无需转成列表/元组),遍历该字符串的每个字符作为新键,值统一沿用原字典的'hello'。

方法二:基础循环实现

D = {'name': 'hello'}
new_dict = {}
target_key = next(iter(D))
target_value = D[target_key]
for c in target_key:
    new_dict[c] = target_value
  • 说明:先取出原字典的键和值,再遍历键的每个字符,逐个添加到新字典中,全程未使用list、tuple、append方法。

两种方法运行后都能得到预期输出:{'n': 'hello', 'a': 'hello', 'm': 'hello', 'e': 'hello'}

内容的提问来源于stack exchange,提问作者Leela Mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:02