我需要字典输出,不使用列表、元组、append

-2 投票
4 回答
55 浏览
提问于 2025-04-14 18:37
D={'name':'hello'}

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

需要这个输出,写一段不使用列表、元组和append的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'}

4 个回答

0

你似乎是在遍历字典里的值,而不是键:

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

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

按照要求输出。

2
d = {'name': 'hello'}
print(dict.fromkeys(*d.popitem()))
{'n': 'hello', 'a': 'hello', 'm': 'hello', 'e': 'hello'}

输出结果(在线尝试这个!):

0

试试这个:

D = {"name": "hello"}

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

输出结果是:

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

撰写回答