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}
您似乎正在迭代字典中的值而不是键:
d = {'name': 'hello'}
output = {}
key = 'name'
for char in key:
output[char] = d[key]
print(output)
按要求输出。
尝试:
out = dict.fromkeys(D["name"], D["name"])
print(out)
打印:
{"h": "hello", "e": "hello", "l": "hello", "o": "hello"}