Delete key,values嵌套字典在python 2.7中

问题描述 投票:0回答:1
a={'name': 'mark',
 'ip': '17.25.888.63',
 'address': [{'state': 'texas',
   'city': 'Addison',
   'county': 'Dallas County'}],
 'stadium_address': [{'address': 'San Jacinto Blvd',
   'city': 'Austin'}],
   'country': 'United States'}

需要从嵌套字典中删除'city': 'Addison'。从普通字典尝试过del dict['ip'],它正在删除,但是当我为嵌套字典尝试相同的操作时,我正在获取TypeError: list indices must be integers or slices, not str

python python-2.7 dictionary nsdictionary
1个回答
0
投票

“ address”和“ stadium_address”是词典列表,而不是词典列表。要进入嵌套词典,必须首先访问列表。例如,可以通过以下方式访问“ address.city”:

dict['address'][0]['city']

这是假设列表中的第一个元素是您想要的元素,情况可能并非总是如此。如果不是,则将需要其他逻辑来确定要使用哪个元素。添加其他错误检查逻辑,例如查看列表是否为空,也是明智的。

© www.soinside.com 2019 - 2024. All rights reserved.