Python dictionary key assign -
Python dictionary key assign -
i've created dictionary tuple, can't seem find reply how i'd switch keys , values without editing original tuple. have far:
tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')] dic = dict(tuples) print dic
this gives output:
{'a': '1', 'b': ''1', 'c': '2', 'd': '3'}
but i'm looking for:
{'1': 'a' 'b', '2': 'c', '3': 'd'}
is there simple code produce this?
build dictionary in loop, collecting values lists:
result = {} value, key in tuples: result.setdefault(key, []).append(value)
the dict.setdefault()
method set , homecoming default value if key isn't present. here used set default empty list value if key not present, .append(value)
applied list object, always.
don't seek create mix of single string , multi-string list values, you'll complicate matters downwards road.
demo:
>>> tuples = [('a', '1'), ('b', '1'), ('c', '2'), ('d', '3')] >>> result = {} >>> value, key in tuples: ... result.setdefault(key, []).append(value) ... >>> result {'1': ['a', 'b'], '3': ['d'], '2': ['c']}
python dictionary tuples
Comments
Post a Comment