所以,我有一个for循环来创建一些字典。除此之外,我想把这些词典添加到一个列表中。for循环工作得很好,我可以单独打印字典,但是当我尝试将它们附加到列表中时,我没有得到想要的结果。我只是不知道我做错了什么。任何帮助都将不胜感激
# This is the dictionary I'll be altering:
user = {'user': 'nikos', 'areas': [{'Africa': ['Kenya', 'Egypt']}, {'Europe': ['Brexit']}]}
# these are some needed variables
user_new = [] # where the dictionaries will be added
sample_user = {}
这是我的密码:
for i in user['areas']:
sample_user['user'] = user['user']
for key in i:
sample_user['area'] = key #ok
kword = i.get(key)
kword = '$'.join(kword)
sample_user['keywords'] = kword
user_new.append(sample_user)
print(user_new)
print()
的期望结果是:
[{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'},
{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}]
但我有两张单子:
[{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'}]
[{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}, {'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'}]
如果您想坚持现有的代码,只需在循环内移动
sample_user = {}
(而在循环外移动print()
)。所以代码是:因为现在你只是在重写同一本字典
使用简单的迭代
例如:
输出:
相关问题 更多 >
编程相关推荐