我設法抓取了一些內容并將其組織為這樣的嵌套字典。
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"
}
]
}
}
提前感謝任何可以教我的提示。
uj5u.com熱心網友回復:
嘗試這個。我剛剛在你的邏輯中添加了索引。它將根據索引選擇用戶名
idx = 0
tw_usernames = ['@user1', '@user2']
for firstdict in country_data.values():
for dictpeople in firstdict.values():
for name in dictpeople:
name['Twitter'] = tw_usernames[idx]
idx =1
print(country_data)
輸出
{
"US":{
"People":[
{
"Title":"Pres.",
"Name":"Joe",
"Twitter":"@user1"
},
{
"Title":"Vice",
"Name":"Harris",
"Twitter":"@user2"
}
]
}
}
uj5u.com熱心網友回復:
您可以使用用戶名串列壓縮子字典串列,并迭代生成的對序列以Twitter向每個子字典添加一個鍵:
for person, username in zip(country_data['US']['People'], tw_usernames):
person['Twitter'] = username
使用您的樣本輸入,country_data將變為:
{'US': {'People': [{'Title': 'Pres.', 'Name': 'Joe', 'Twitter': '@user1'}, {'Title': 'Vice', 'Name': 'Harris', 'Twitter': '@user2'}]}}
uj5u.com熱心網友回復:
源代碼
def add_twitter_usernames_to_users(country_data: dict, tw_usernames: [str]):
for tw_username in tw_usernames:
country_data["US"]["People"][tw_usernames.index(tw_username)]["Twitter"] = tw_username
return country_data
測驗
def test_add_twitter_usernames_to_users():
country_data = {
"US": {
"People": [
{
"Title": "Pres.",
"Name": "Joe"
},
{
"Title": "Vice",
"Name": "Harris"
}
]
}
}
tw_usernames = ['@user1', '@user2']
updated_country_data: dict = so.add_twitter_usernames_to_users(country_data, tw_usernames)
assert updated_country_data["US"]["People"][0]["Twitter"] == "@user1"
assert updated_country_data["US"]["People"][1]["Twitter"] == "@user2"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368171.html
上一篇:字典被新輸入覆寫
下一篇:根據鍵名拆分字典
