Q:

Python dictionary key assign

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?

A:

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']}

