[英]how to combine keys of a dictionary when the values are the same?
I am trying to combine the keys of a dictionary when the values are the same as below,I am trying as below it only prints the values of the dictionary, any guidance how to fix this?当值与以下相同时,我正在尝试组合字典的键,我正在尝试如下它只打印字典的值,任何指导如何解决这个问题?
final_BATS_container_id_list = [
{'Rome_Nightly': ['15715489']},
{'Rome': ['15715490']},
{'Italy': ['15715491']},
{'Paris': ['15715491']},
{'France': ['15715491']},
{'Italy_Escape': ['15715493']},
{'Paris_Escape': ['15715493']},
{'France_Escape': ['15715493']}]
new_key = ''
for BATS_container_id_dict in final_BATS_container_id_list:
for key,value in BATS_container_id_dict.items():
print('key %s => value %s'%(key,value))
Expected output:-预期输出:-
[{'Rome_Nightly': ['15715489']},
{'Rome': ['15715490']},
{'Italy/Paris/France': ['15715491']},
{'Italy_Escape/Paris_Escape/France_Escape': ['15715493']}]
You can use a defaultdict to invert the key/value relationship and accumulate the keys that are associated with values.您可以使用defaultdict来反转键/值关系并累积与值关联的键。 Then a simple list comprehension will make the desired list of dicts for you:
然后一个简单的列表理解将为您制作所需的字典列表:
from collections import defaultdict
l = [
{'Rome_Nightly': ['15715489']},
{'Rome': ['15715490']},
{'Italy': ['15715491']},
{'Paris': ['15715491']},
{'France': ['15715491']},
{'Italy_Escape': ['15715493']},
{'Paris_Escape': ['15715493']},
{'France_Escape': ['15715493']}]
groups = defaultdict(list)
for d in l:
for k, v in d.items():
groups[v[0]].append(k)
result = [{'/'.join(v): [k]} for k, v in groups.items()]
Giving you a result
of:给你一个
result
:
[{'Rome_Nightly': ['15715489']},
{'Rome': ['15715490']},
{'Italy/Paris/France': ['15715491']},
{'Italy_Escape/Paris_Escape/France_Escape': ['15715493']}]
final_BATS_container_id_list = [
{'Rome_Nightly': ['15715489']},
{'Rome': ['15715490']},
{'Italy': ['15715491']},
{'Paris': ['15715491']},
{'France': ['15715491']},
{'Italy_Escape': ['15715493']},
{'Paris_Escape': ['15715493']},
{'France_Escape': ['15715493']}
]
value_map = {}
for item in final_BATS_container_id_list:
for key, value in item.items():
first = value[0] # eg. ['15715493'][0]. caution: index out of bounds
vv = value_map.get(first, [])
vv.append(key)
value_map[first] = vv
result = []
for key in value_map.keys():
joined = '/'.join(value_map[key]) # eg. Italy/Paris/France
result.append({joined: [key]})
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.