【问题标题】:How to change the value of a key in a nested dictionary in Python [closed]如何在Python中更改嵌套字典中键的值[关闭]
【发布时间】:2018-12-01 22:52:13
【问题描述】:
{
 {'city':1 ,'person':{'name': 'John', 'age': '27'}},
 {'city':2 ,'person':{'name': 'Marie', 'age': '22'}},
 {'city':3 ,'person':{'name': 'Luna', 'age': '24'}},
 {'city':4 ,'person':{'name': 'Peter', 'age': '29'}}
}

如何更改城市 2 中的人的年龄?

我的问题的第二部分是在 Python 中,在这种情况下哪种数据结构最相关

【问题讨论】:

  • 这不是字典。
  • 这样更好。但是你只是想修改data[1]的人的年龄,还是你还需要找到'city':2的dict,以防你不知道它在列表中的位置?
  • 需要先找到 'city':2 的字典
  • 您还没有向我们展示您编写此代码的尝试。我没有投反对票,但这可能是您的问题获得这么多反对票的主要原因。
  • @Barny 请不要使用提供的答案修复您的问题代码,否则该问题对未来的用户毫无意义。

标签: python list dictionary data-structures


【解决方案1】:

你最好使用字典列表,并将age整数:

data = [
 {'city':1, 'person': {'name': 'John', 'age': 27}},
 {'city':2, 'person': {'name': 'Marie', 'age': 22}},
 {'city':3, 'person': {'name': 'Luna', 'age': 24}},
 {'city':4, 'person': {'name': 'Peter', 'age': 29}}
]
person_by_city_id = {item['city_id']: item['person'] for item in data}
person_by_city_id[2]['age'] = 23

但是数据方案很奇怪(如果我们有来自一个城市的 2 个人 - 我们需要更改哪个年龄?)

【讨论】:

  • @PM2Ring 谢谢,更新了我的代码
猜你喜欢
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 2011-07-02
  • 2022-08-22
相关资源
最近更新 更多