【发布时间】:2022-01-04 09:11:56
【问题描述】:
我设法抓取了一些内容并将其组织成这样的嵌套字典。
country_data = {
"US": {
"People": [
{
"Title": "Pres.",
"Name": "Joe"
},
{
"Title": "Vice",
"Name": "Harris"
}
]
}
}
然后我有这个列表
tw_usernames = ['@user1', '@user2']
我想用它来将每个项目列表添加到 People 嵌套字典的每个条目中。我已经对列表和字典理解做了一些研究,但我找不到使它起作用的东西,所以我尝试使用这个基本代码,但它当然不是我想要的,因为它返回所有项目列表。
for firstdict in country_data.values():
for dictpeople in firstdict.values():
for name in dictpeople:
name['Twitter'] = tw_usernames
print(name)
那么你会怎么做才能得到这样的字典呢?
country_data = {
"US": {
"People": [
{
"Title": "Pres.",
"Name": "Joe",
"Twitter": "@user1"
},
{
"Title": "Vice",
"Name": "Harris",
"Twitter": "@user2"
}
]
}
}
提前感谢任何可以教我的提示。
【问题讨论】:
-
您愿意做类似
for name, twitters in zip(dictpeople, tw_usernames):(您的代码示例的第 3 行)之类的事情吗?
标签: python dictionary nested