简体   繁体   English

如何从字典 python 中获取键和值

[英]How to get keys and values from dictionary python

I have my dictionary as per below我有我的字典,如下所示

my_dict = {4: 8, 3: 11, 4: 10, 5: 10, 8: 5, 9: 5, 10: 10, 5: 2}

I am trying to figure out how to get a sorted list when key == value and also when iterating the value becomes the key.我试图弄清楚当key == value以及迭代 value 成为 key 时如何获取排序列表。 The result then is那么结果是

[[2,5,4,8],[10]] [[2,5,4,8],[10]]

Any ideas?有任何想法吗?

Does this work for you:这对你有用吗:

my_dict = {1: 3, 4: 2, 2: 6, 10: 10}

loop_backs = set()
new_dict = my_dict.copy()
for k,v in my_dict.items():
    if k == v:
        loop_backs |= {k}
        del new_dict[k]
repeated = set(new_dict.values()).intersection(new_dict.keys()) | loop_backs
res = set()
for k,v in new_dict.items():
    if (k in repeated) or (v in repeated):
        res |= {k,v}
print(res, loop_backs)

{2, 4, 6} {10} {2、4、6} {10}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM