I have a 2 dictionaries and it contains data like this:
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
I wanted to append only item1['data']
and item2['data']
into the single list, how can I append this?. My expected list is
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}, {'e': 55, 'f': 66}, {'g': 77, 'h': 88}]
CodePudding user response:
You can unpack the list.
>>> item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
>>> item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
>>>
>>> [*item1['data'], *item2['data']]
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}, {'e': 55, 'f': 66}, {'g': 77, 'h': 88}]
Or, you can use list.extend
method.
>>> result = item1['data'].copy()
>>> result
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]
>>> result.extend(item2['data'])
>>> result
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}, {'e': 55, 'f': 66}, {'g': 77, 'h': 88}]
CodePudding user response:
2 of the multiple ways:
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
outlist = item1['data'] item2['data']
print (outlist)
OR
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
outlist = []
for d in item1['data']:
outlist.append(d)
for d in item2['data']:
outlist.append(d)
print (outlist)
Output:
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}, {'e': 55, 'f': 66}, {'g': 77, 'h': 88}]
CodePudding user response:
You can simply try this:
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
final = item1.get('data', '') item2.get('data', '')
print(final)
Output:
[{'a': 11, 'b': 22}, {'c': 33, 'd': 44}, {'e': 55, 'f': 66}, {'g': 77, 'h': 88}]
CodePudding user response:
This is also done by using for loop.
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
for item in item2['data']:
item1['data'].append(item)
print(item1['data'])
CodePudding user response:
Try this script:
a=[]
item1 = {'data': [{'a': 11, 'b': 22}, {'c': 33, 'd': 44}]}
item2 = {'data': [{'e': 55, 'f': 66}, {'g': 77, 'h': 88}]}
for i in range(0,2):
var1=item1['data'][i]
a.append(var1)
for i in range(0, 2):
var1 = item2['data'][i]
a.append(var1)
print(a)