Reputation: 59
I have dictionary with key value like this :
[{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]
I would like to get something like this:
[ {key1 : '1', key2 : 'john'}, {key1 : '2', key2 : 'marvel'}, {key1 : '150', key2 : 'gandalf'}, {key1 : '120', key2 : 'sam'}]
I am stuck, I think to embedded loops but I don't know how.
Upvotes: 1
Views: 77
Reputation: 1924
The most easiest way with 2 loops in list comprehension
no hardcoded lists and no new variables
lst = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]
[dict(zip(el.keys(), v)) for el in lst for k,v in el.items()]
[{'key1': '1', 'key2': '2'},
{'key1': 'john', 'key2': 'marvel'},
{'key1': '150', 'key2': '120'},
{'key1': 'gandalf', 'key2': 'sam'}]
Upvotes: 0
Reputation: 96236
If you literally always have just "key1"
and "key2"
, then:
In [1]: data = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['
...: 150', '120'], "key2" : ['gandalf', 'sam']}]
...:
In [2]: [{"key1":v1, "key2":v2} for d in data for (v1, v2) in zip(d['key1'], d['key2'])]
Out[2]:
[{'key1': '1', 'key2': 'john'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '120', 'key2': 'sam'}]
would do
A more general approach would be something like:
In [5]: [dict(zip(d, vs)) for d in data for vs in zip(*d.values())]
Out[5]:
[{'key1': '1', 'key2': 'john'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '120', 'key2': 'sam'}]
Upvotes: 1
Reputation: 61920
You could use a list comprehension:
data = [{"key1": ['1', '2'], "key2": ['john', 'marvel']}, {"key1": ['150', '120'], "key2": ['gandalf', 'sam']}]
keys = ['key1', 'key2']
result = [dict(zip(keys, items)) for d in data for items in zip(*(d[k] for k in keys))]
print(result)
Output
[{'key2': 'john', 'key1': '1'}, {'key2': 'marvel', 'key1': '2'}, {'key2': 'gandalf', 'key1': '150'}, {'key2': 'sam', 'key1': '120'}]
The above list comprehension is equivalent to the following for loop:
result = []
for d in data:
for items in zip(*(d[k] for k in keys)):
result.append(dict(zip(keys, items)))
Upvotes: 4
Reputation: 7607
list1 = [ {'key1' : '1', 'key2' : 'john'}, {'key1' : '2', 'key2' : 'marvel'}, {'key1' : '150', 'key2' : 'gandalf'}, {'key1' : '120', 'key2' : 'sam'}]
list2 = [{'key1':i['key1'][0], 'key2':i['key2'][0]} for i in list1] + [{'key1':i['key1'][1], 'key2':i['key2'][1]} for i in list1]
list2
[{'key1': '1', 'key2': 'john'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '120', 'key2': 'sam'}]
Upvotes: 0
Reputation: 542
result = [{}]
for item in data:
key, val = item.split(":", 1)
if key in result[-1]:
result.append({})
result[-1][key] = val
Upvotes: 0