如何更新字典,以便如果键 'a' 的值为 'c' 而不是 'c' 的键附加值 'a'?
How can I update a dictionary so that if key 'a' has a value of 'c' than the key of 'c' appends the value 'a'?
如果键 'a'
的值为 'c'
,则 'c'
的键应附加 'a'
。请注意,与键 'a'
关联的值不包含在追加中。
我似乎无法弄清楚如何自动执行此过程以在大型词典上执行。
mydict = {
'a': ['z', 'c'],
'b': ['y', 'c'],
'c': ['q', 'r']
}
这是我想要的结果:
mydict = {
'a': ['z', 'c'],
'b': ['y', 'c'],
'c': ['q', 'r', 'a', 'b']
}
for k in mydict:
for val in mydict[k]:
if val in mydict:
mydict[val] += [k]
这是执行此操作的另一种方法,使用集合交集,并保持 parent/children 关系的中间映射。
from collections import defaultdict
d = defaultdict(list)
keys = set([*mydict])
for k, v in mydict.items():
intersected = keys & set(v)
for i in intersected:
d[i].append(k)
print(d)
# defaultdict(list, {'c': ['b', 'a']})
for found, value in d.items():
mydict[found].extend(value)
print(mydict)
# {'a': ['z', 'c'], 'b': ['y', 'c'], 'c': ['q', 'r', 'b', 'a']}
如果键 'a'
的值为 'c'
,则 'c'
的键应附加 'a'
。请注意,与键 'a'
关联的值不包含在追加中。
我似乎无法弄清楚如何自动执行此过程以在大型词典上执行。
mydict = {
'a': ['z', 'c'],
'b': ['y', 'c'],
'c': ['q', 'r']
}
这是我想要的结果:
mydict = {
'a': ['z', 'c'],
'b': ['y', 'c'],
'c': ['q', 'r', 'a', 'b']
}
for k in mydict:
for val in mydict[k]:
if val in mydict:
mydict[val] += [k]
这是执行此操作的另一种方法,使用集合交集,并保持 parent/children 关系的中间映射。
from collections import defaultdict
d = defaultdict(list)
keys = set([*mydict])
for k, v in mydict.items():
intersected = keys & set(v)
for i in intersected:
d[i].append(k)
print(d)
# defaultdict(list, {'c': ['b', 'a']})
for found, value in d.items():
mydict[found].extend(value)
print(mydict)
# {'a': ['z', 'c'], 'b': ['y', 'c'], 'c': ['q', 'r', 'b', 'a']}