如何将for循环中的字典添加到列表中(具体示例)

2024-05-19 03:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一个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'}]

Tags: samplekeynewfor字典areaeuropekeywords
2条回答

如果您想坚持现有的代码,只需在循环内移动sample_user = {}(而在循环外移动print())。所以代码是:

for i in user['areas']:
    sample_user = {}
    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)

因为现在你只是在重写同一本字典

使用简单的迭代

例如:

user = {'user': 'nikos', 'areas': [{'Africa': ['Kenya', 'Egypt']}, {'Europe': ['Brexit']}]}   
result = []

for i in user["areas"]:
    val = list(i.items())
    result.append({"user": user["user"], 'area': val[0][0], 'keywords': "$".join(val[0][1])})
print(result)

输出:

[{'area': 'Africa', 'keywords': 'Kenya$Egypt', 'user': 'nikos'},
 {'area': 'Europe', 'keywords': 'Brexit', 'user': 'nikos'}]

相关问题 更多 >

    热门问题