Search code examples
pythonnested-lists

Python - Create Dictionary From Nested List and Dictionaries


I'm trying to create a dictionary from values within dictionaries within lists. See the following example:

dict1={'x':1,'y':7}
dict2={'x':2,'y':8}
dict3={'x':3,'y':9}

list1=[dict1,dict2,dict3]
list2=[dict3]
list3=[dict2,dict3]

A=[list1,list2,list3]

How do I loop through the lists and dicts to create a new dict for {x:y}?

newdict={A[0][0]['x']:A[0][0]['y'] ,..., A[2][1]['x']:A[2][1]['y']}

I tried:

newdict={}
for i in A:
   newdict[i]={A[i][j]['x']:A[i][j]['y'] for j in A[i]}

But I got an error "list indices must be integers or slices, not list"


Solution

  • Something like this:

    foo_dict = {'x': 1, 'y': 2, 'z': 3}
    inner_list = [foo_dict]
    outer_list = [inner_list]
    
    newdict = {d['x']: d['y'] for inner in outer_list for d in inner}
    # => {1: 2}
    

    Using your recently added example:

    all_xy = {d['x']: d['y'] for inner in A for d in inner}
    # => {1: 7, 2: 8, 3: 9}