简体   繁体   English

如何使用正确的键/值更新字典中的图表?

[英]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.

相关问题 我如何更新字典,以便如果键“ 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'? 如何在python中更新字典中的值? - How can I update a value in a dictionary in python? 如何使用变量中的值更新嵌套 Python 字典中的键? - How can i update key in nested Python dictionary with a value from a variable? 如果键是一个元组,如何在字典中访问键的值? - How can I access the value of a key in a dictionary if the key is a tuple? 如何使用for循环操作键以更新字典 - how can I manipulate key with for loops to update dictionary 如何将列表中的值引用到字典键值? - How can I reference a value from a list to the dictionary key value? 如果 value 与给定字典中的 key 相等,我怎么能 append 到 key 的 value 的第一个 key - If value is equal with a key in the given dictionary, how can I append to the key of the said value the value of the first key 更新字典中键的值 - update the value of key in a dictionary 更新字典中键的值 - update value of a key in a dictionary 如何在Python中更新字典值,让用户选择要更新的密钥,然后选择新值? - How do I update a dictionary value having the user choose the key to update and then the new value, in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM