Skip to content Skip to sidebar Skip to footer

Append Python List Of Dictionaries By Loops

I have 2 Python List of Dictionaries: [{'index':'1','color':'red'},{'index':'2','color':'blue'},{'index':'3','color':'green'}] & [{'device':'1','name':'x'},{'device':'2','n

Solution 1:

I think that the following code answers your question:

indexes = [
    {'index':'1','color':'red'},
    {'index':'2','color':'blue'},
    {'index':'3','color':'green'}
]
devices = [
    {'device':'1','name':'x'},
    {'device':'2','name':'y'},
    {'device':'3','name':'z'}
]
new_lists = [[device] fordevicein devices]
fornew_listin new_lists:
    new_list.extend(indexes)

Solution 2:

I don't know where you wanted to save your result lists, so I printed them out:

d1 = [{'index':'1','color':'red'},{'index':'2','color':'blue'},{'index':'3','color':'green'}]   
d2 = [{'device':'1','name':'x'},{'device':'2','name':'y'},{'device':'3','name':'z'}]

for item in d2:
    print ([item] + d1)

The output:

[{'name': 'x', 'device': '1'}, {'index': '1', 'color': 'red'}, {'index': '2', 'color': 'blue'}, {'index': '3', 'color': 'green'}] [{'name': 'y', 'device': '2'}, {'index': '1', 'color': 'red'}, {'index': '2', 'color': 'blue'}, {'index': '3', 'color': 'green'}] [{'name': 'z', 'device': '3'}, {'index': '1', 'color': 'red'}, {'index': '2', 'color': 'blue'}, {'index': '3', 'color': 'green'}]

(Don't be confused by order of items in individual directories as directories are not ordered.)

Post a Comment for "Append Python List Of Dictionaries By Loops"