I have dictionary
[{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
I want to create resultant dictionary
result = {'tc1':['tc2', 'tc3']}
Any idea how we can do that?
js = [{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
ls =[]
for i in js:
x[i['a']]= ls+[(i["b"])]
If I understood your question correctly, the 'a' element will always be the key for the new dictionary, and the 'b' element, its value. Then the following code should work for you:
js = [{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
result = {} # Create the empty result dictionary
for i in js:
k, v = i['a'], i['b'] # k will be the key, v will be the value
if k not in result: # If k is not a key of result yet, we create the entry as an empty list
result[k] = []
# By now, we know that k is a key in result. Now we add the value.
result[k].append(v)
print result # {'tc1': ['tc2', 'tc3']}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments