简体   繁体   中英

How to remove duplicated keys in reverse order from dictionary (python)

I am struggling to remove same keys from a dictionary in the case below:

{('cat', 'tiger'): 18,
 ('tiger', 'cat'): 18,
 ('chines', 'gentleman'): 7,
 ('gentleman', 'chines'): 7}

In this case, I consider reverse order ('cat', 'tiger'): 18 and ('tiger', 'cat'): 18 as same keys and try to make a new dictionary like below

 {('cat', 'tiger'): 18,
  ('gentleman', 'chines'): 7}

What I am trying is adapt any reverse order case, when I have a similar dictionary like {(('cage', 'cat'), 5),(('cat', 'cage'), 5)} to be merged or removed, either one.

You could do something along the following lines:

d = {('cat', 'tiger'): 18,
     ('tiger', 'cat'): 18,
     ('chines', 'gentleman'): 7,
     ('gentleman', 'chines'): 7}

result = {tuple(sorted(x)): y for x, y in d.items()}
# {('cat', 'tiger'): 18, ('chines', 'gentleman'): 7}

In this dict comprehension, the last encountered value for each set of "equal" keys wins. With your sample data, this shouldn't matter because those keys have equla values. Note that this also just sorts the tuples, regardless of the sorted version actually occuring in the original dict .

The problem is that you are using tuple values as keys, but tuple objects are ordered, so ('a','b') is different than ('b','a') . A simple solution? Use an unordered yet hashable container, ie a frozenset would work:

>>> data = {('cat', 'tiger'): 18,
...  ('tiger', 'cat'): 18,
...  ('chines', 'gentleman'): 7,
...  ('gentleman', 'chines'): 7}
>>>
>>> data
{('cat', 'tiger'): 18, ('tiger', 'cat'): 18, ('chines', 'gentleman'): 7, ('gentleman', 'chines'): 7}
>>> {frozenset(k):v for k,v in data.items()}
{frozenset({'cat', 'tiger'}): 18, frozenset({'gentleman', 'chines'}): 7}

If you do not care about the order of the two items in the key... and the value associated with them is always the same, the easiest would probably be, assuming your starting dictionary named old_dict :

new_dict = dict()
for (key, value) in old_dict.items():
    new_dict[tuple(sorted(key))] = value

You just iterate through key/value pairs and add them into new_dict . Since we now sorted the key and then turned the resulting list back into tuple, we make sure than any reappearing couple just overwrites the previous entry.

instead of deleting items from that , you can take what you want and leave rest.

data={('cat', 'tiger'): 18,
 ('tiger', 'cat'): 18,
 ('chines', 'gentleman'): 7,
 ('gentleman', 'chines'): 7}


track={}
for i,j in data.items():
    track[tuple(sorted(i))]=j

print(track)

output:

{('cat', 'tiger'): 18, ('chines', 'gentleman'): 7}

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.

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