l1=[{"key1":["value1"]},{"key2":["value2"]},{"key3":["value3"]}]
convert and swap key to value and value to key...
the desired output should be:
d1={"value1":"key1","value2":"key2","value3":"key3"}
CodePudding user response:
Use a dictionary comprehension:
d1 = {v[0]:k for d in l1 for k,v in d.items()}
output: {'value1': 'key1', 'value2': 'key2', 'value3': 'key3'}
Note that, as dictionary keys are unique, this cannot handle a case were you would have several times the same value. This would only consider the last occurrence.
CodePudding user response:
Since each sub-dict contains exactly one key-value pair, you can unpack the dict items according to the fixed structure and reconstruct the key-value pairs with a dict comprehension:
{v: k for [(k, [v])] in map(dict.items, l1)}