-3

I've created a dictionary from a tuple, but can't seem to find an answer as to how I'd switch my keys and values without editing the original tuple. This is what I have so far:

tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')]

dic = dict(tuples)

print dic

This gives the output:

{'a': '1', 'b': ''1', 'c': '2', 'd': '3'}

But I'm looking for:

{'1': 'a' 'b', '2': 'c', '3': 'd'}

Is there a simple code that could produce this?

Eeconyn
  • 57
  • 1
  • 2
  • 4

2 Answers2

2

Build a dictionary in a loop, collecting your values into lists:

result = {}

for value, key in tuples:
    result.setdefault(key, []).append(value)

The dict.setdefault() method will set and return a default value if the key isn't present. Here I used it to set a default empty list value if the key is not present, so the .append(value) is applied to a list object, always.

Don't try to make this a mix of single string and multi-string list values, you'll only complicate matters down the road.

Demo:

>>> tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')]
>>> result = {}
>>> for value, key in tuples:
...     result.setdefault(key, []).append(value)
... 
>>> result
{'1': ['a', 'b'], '3': ['d'], '2': ['c']}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Plus eleventy billion to "Don't try to make this a mix of single string and multi-string list values, you'll only complicate matters down the road." – PM 2Ring Oct 17 '14 at 12:17
0
from operator import itemgetter
from itertools import groupby
first = itemgetter(0)
second = itemgetter(1)
d = dict((x, [v for _, v in y]) for x, y in groupby(sorted(tuples, key=second), key=second)

groupby groups the tuples into a new iterator of tuples, whose first element is the unique second item of each of the original, and whose second element is another iterator consisting of the corresponding first items. A quick example (pretty-printed for clarity):

>>> list(groupby(sorted(tuples, key=second), key=second)))
[('1', <itertools._grouper object at 0x10910b8d0>), 
 ('2', <itertools._grouper object at 0x10910b790>),
 ('3', <itertools._grouper object at 0x10910b750>)]

The sorting by the same key used by groupby is necessary to ensure all like items are grouped together; groupby only makes one pass through the list.

The subiterators consist of tuples like ('1', 'a'), so the second value in each item is the one we want to add to the value in our new dictionary.

chepner
  • 497,756
  • 71
  • 530
  • 681