我需要在字典中输出而不使用列表,元组,追加

问题描述 投票:0回答:2
D={'name':'hello'}

output = {'n':'hello','a':'hello','m':'hello','e':'hello'}

需要这个输出编写一个不使用列表、元组、追加的Python代码

d = {'name': 'Hello'}
output = {}

for char in d['name']:
  output[char] = 'hello'
print(output)

但是我得到了这个输出=

{'H': 'hello', 'e': 'hello', 'l': 'hello', 'o': 'hello'}

我期待输出=

{'n':'hello','a':'hello','m':'hello','e'='hello}

python python-3.x python-2.7
2个回答
0
投票

您似乎正在迭代字典中的值而不是键:

d = {'name': 'hello'}
output = {}

key = 'name'
for char in key:
  output[char] = d[key]
print(output)

按要求输出。


0
投票

尝试:

out = dict.fromkeys(D["name"], D["name"])
print(out)

打印:

{"h": "hello", "e": "hello", "l": "hello", "o": "hello"}
© www.soinside.com 2019 - 2024. All rights reserved.