[英]How can I update a graph in a Dictionary with right key/value?
Hi all I have a graph in a dictionary and I would like to update the key/value in order to not skip "5" which is a node that has been previously removed, and so make 6 and 7 become 5 and 6 and so update also the value since this is a graph大家好,我在字典中有一个图表,我想更新键/值以便不跳过“5”,这是一个先前已删除的节点,因此使 6 和 7 变为 5 和 6 等更新也是值,因为这是一个图表
{'1': ['2', '3', '6'], '3': ['1', '2', '4'], '2': ['3', '4'], '4': ['2', '3'], '7': ['6'], '6': ['1', '7']}
The output that I would like to aspect should be this:我想介绍的 output 应该是这样的:
{'1': ['2', '3', '5'], '3': ['1', '2', '4'], '2': ['3', '4'], '4': ['2', '3'], '6': ['5'], '5': ['1', '6']}
basically rescale everything with respect to the key/node that has been removed.基本上重新调整与已删除的键/节点有关的所有内容。
You can use this:你可以使用这个:
mapping = {'6': '5', '7': '6'}
result = {}
for key, value in graph.items():
val = [mapping.get(val, val) for val in value]
k = mapping.get(key, key)
result[k] = val
print(result)
Which gives:这使:
{'1': ['2', '3', '5'], '3': ['1', '2', '4'], '2': ['3', '4'], '4': ['2', '3'], '6': ['5'], '5': ['1', '6']}
The equivalent one-liner is:等效的单线是:
>>> result = {mapping.get(key, key): [mapping.get(v, v) for v in values]
for key, values in graph.items()}
Another solution could be:另一种解决方案可能是:
def get_ordered_dict(_dict):
return dict(sorted(_dict.items()))
mydict = {'1': ['2', '3', '6'], '3': ['1', '2', '4'], '4': ['2', '3'], '7': ['6'], '2': ['3', '4'], '6': ['1', '7']}
mydict.update({'5': ['2', '3', '6']})
newdict = get_ordered_dict(mydict)
print(newdict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.