How to Exchange Keys with Values in a Dictionary

How do I exchange keys with values in a dictionary?

Python 2:

res = dict((v,k) for k,v in a.iteritems())

Python 3 (thanks to @erik):

res = dict((v,k) for k,v in a.items())

switching keys and values in a dictionary in python

For Python 3:

my_dict2 = {y: x for x, y in my_dict.items()}

For Python 2, you can use

my_dict2 = dict((y, x) for x, y in my_dict.iteritems())

Best way to exchange keys with values in a dictionary, where values are in a list?

Your setdefault code is almost there, you just need an extra loop over the lists of values:

res = {}

for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)

Change the name of a key in dictionary

Easily done in 2 steps:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1

Swap dictionary keys and values when values are lists

You can use a dictionary comprehension and the .items() method.

In []: {k: oldk for oldk, oldv in swapdict.items() for k in oldv}
Out[]: {'a': 'foo', 'b': 'foo', 'c': 'bar', 'd': 'bar'}

Swapping key-value pairs in a dictionary

But for this I would have to use extra space for declaring another dictionary.

Since a dictionary is essentially a lookup table, there is a concrete way it is layed out in memory; the keys are distributed efficiently and just point to values which—by themselves—have no special meaning. Thus, when you want to reverse the mapping, you can’t really use the existing structure; instead you will have to create new dictionary entries from scratch. The dictionary comprehension you have used in your question is a good and clear way to do that.

What you could do however is to reuse the dictionary you already have and add the new keys there (while removing the old ones):

for k in a:
a[a[k]] = k
del a[k]

This modifies the same dictionary, so it won’t have the (likely little) overhead of a new dictionary. Note that this assumes that all values are unique too so the mapping can be exactly reversed, and that the set of keys and values don’t share common values. Otherwise, you will run into dictionary size changed exceptions or missing values. You can avoid the former by creating a copy of the dictionary keys (although this means that you have a list to store now too):

for k in list(a):
if a[k] != k:
a[a[k]] = k
del a[k]

A final note: It’s possible that modifying the dictionary multiple times like that might have some remapping side-effects though (to increase the hash table size etc.), but that’s possible implementation detail of CPython (and I’m not too sure about it).

swap key value pairs in a dictionary with values as lists

Use defaultdict:

In [30]: d={1:[0,1,2,3,4],2:[1,3]}

In [31]: from collections import defaultdict
In [32]: out = defaultdict(list)
In [33]: for k, v in d.items():
...: for vv in v:
...: out[vv].append(k)
...:

In [34]: dict(out)
Out[34]: {0: [1], 1: [1, 2], 2: [1], 3: [1, 2], 4: [1]}


Related Topics



Leave a reply



Submit