【发布时间】:2021-10-02 21:12:26
【问题描述】:
我一直在处理列表,以便更好地理解它们。首先,这些数据是从我发出的请求调用中收集的。我遇到了这样的想法,即拥有两个具有相似键和值的列表。 List one 有一个字典,其键 state: city 有两个值,而 list two 缺少其中一个值。另一方面,list two 有一个来自字典键state: city 的额外值,而不是list one。对于第一段代码,我想用list one 中的缺失值更新list two。对于第二段代码,我想从list two 中删除list one 上缺少的额外值
这是我目前拥有的。
list_one = [
{
'name': 'California',
'state': [{'id': '34567', 'city': 'LA'}, {'id': '67890', 'city': 'San Francisco'}],
'region': 'W'
},
{
'name': 'Texas',
'state': [{'id': '45678', 'city': 'Austin'}],
'region': 'SW'
},
{
'name': 'New York',
'state': [{'id': '56789', 'city': 'Brooklyn'}],
'region': 'E'
}
]
list_two = [
{
'name': 'California',
'state': [{'id': '12345', 'city': 'Miami'}],
'region': 'W'
},
{
'name': 'Texas',
'state': [{'id': '23456', 'city': 'Austin'}, {'id': '78901', 'city': 'Houston'}],
'region': 'E'
},
{
'name': 'New York',
'state': [{'id': '01234', 'city': 'Brooklyn'}],
'region': 'E'
}
]
#update - if list_one has cities not in list_two, add those
for state1 in list_one:
for state2 in list_two:
for city1 in state1['state']:
for city2 in state2['state']:
res = [i['state'] for i in list_one if i not in list_two]
if city1['city'] not in city2['city']:
city2['city'] = city1['city']
#delete - if list_one doesn't have the city in list_two, delete it from
#list_two
elif city2['city'] not in city1['city']:
old_city2 = city2
res2 = [i['state'] for i in list_two if i not in list_one]
# city2['city'].remove()
我觉得我做的太多了,可能会更简单。至于id,我不想只更新cities。如果我需要删除一个`city,那么我想删除整个字典元素。
谢谢!
【问题讨论】:
-
我知道您正在努力学习,但这种布局只是在乞求 SQL 数据库。如果是我,
list_one将是一个字典,其中键是州名,值是带有region和城市 ID 的字典,可以在cities字典中查找。 -
其实我没有提到这个,但是这是来自一个API调用。我只是将数据复制到 python 中,所以我可以使用它而无需请求它。虽然,我很欣赏你的评论,谢谢。
标签: python list loops dictionary if-statement