【问题标题】:Add same key but different values (coming from list) to a nested dictionary将相同的键但不同的值(来自列表)添加到嵌套字典
【发布时间】: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


【解决方案1】:

试试这个。我刚刚在您的逻辑中添加了索引。它会根据索引选择用户名

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"
         }
      ]
   }
}

【讨论】:

  • 嗨哈希尔,感谢您的贡献。我试过了,但实际上我得到了这个错误:name['Twitter'] = tw_usernames[idx] IndexError: list index out of range
  • 提供的给定数据对我来说效果很好。我猜你的 tw_usernames 列表的大小和人员列表的大小不一样。在这种情况下,我们必须进行额外检查
  • 你是对的!在给定的示例中,只有 2 个人,但在我的代码中,我有一个不同的数字。感谢您的检查:)
【解决方案2】:

您可以使用用户名列表压缩子字典列表,并遍历生成的对序列以向每个子字典添加 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'}]}}

【讨论】:

  • 可爱!谢谢@blhsing。它适用于这个例子,我将看看如何让它在 for 循环中工作,因为你可以想象,字典包含其他国家。
【解决方案3】:

源代码

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"

【讨论】:

  • 谢谢老兄,我的功能还不是很擅长,但我一定会看看你的建议。
猜你喜欢
  • 1970-01-01
  • 2021-08-21
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多