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. The result then is
[[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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.