You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将列表元素作为相同键的不同值添加到Python嵌套字典中

问题原因

你原有代码的问题是在循环中直接将整个tw_usernames列表赋值给了每个字典的Twitter字段,没有做元素和字典条目之间的一一对应,才会出现不符合预期的结果。

实现方案

使用Python内置的zip()函数将People列表的字典条目和tw_usernames的元素按位置配对,逐个赋值即可。

写法1:适配多国家的通用写法

如果你的country_data后续会添加多个国家数据,用这个写法可以兼容所有国家的People字段处理:

for country_detail in country_data.values():
    people_list = country_detail["People"]
    # 一对一配对人员字典和Twitter用户名
    for person_dict, twitter_id in zip(people_list, tw_usernames):
        person_dict["Twitter"] = twitter_id

写法2:固定结构简化写法

如果你的数据结构固定只有US下的People字段,可以直接定位操作,写法更简洁:

for person_dict, twitter_id in zip(country_data["US"]["People"], tw_usernames):
    person_dict["Twitter"] = twitter_id

注意事项

  • 该写法默认tw_usernames的长度和People列表的长度完全一致,如果二者长度不同,zip()会自动以更短的序列长度为准做截断
  • 以上操作都是直接修改原字典,不需要额外生成新的country_data对象,运行后直接打印country_data即可得到你要的目标格式

内容的提问来源于stack exchange,提问作者arkanjie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:36:00