Python dictionary key assign -
I have created a dictionary from a topless, but I think how will I switch without editing the original Tupal The keys and the value that I have done so far:
Tulips = [('A', '1'), ('B', '1'), ('C' '2')
This output returns:
{'a': ('D', '3')] dic = dict (tuples ) I am looking for it: '1', 'B': '1', 'C': '2', 'D': '3'} < / P> {'1': 'a' 'b', '2': 'c', '3': 'd'}
Simple code Land that could cause this?
Create a dictionary in the loop, store your values in lists:
< Code> result = {} for value, key in tuples: result.setdefault (key, []) .andend (value)
set and return will default value if key does not exist Here I used to set the default empty list value, if the key is not present, then .append (value)
always applies to the list object.
Don 'do not try to mix a single string and multi-string list values, you will only complicate the matter under the road.
Demo:
& gt; & Gt; & Gt; Tuples = [('A', '1'), ('B', '1'), ('C', '2'), ('D', '3')]> gt; & Gt; & Gt; Results = {}> gt; & Gt; & Gt; For the price, the key in Tuples: ... result.setdefault (key, []). Attachment (value) ... & gt; & Gt; & Gt; Result {'1': ['A', 'B'], '3': ['D'], '2': ['c']}
Comments
Post a Comment