Getting the values of a dictionary contained in a list of lists

Viewed 66

Having a list like:

my_list = [
  [{'score':9, 'name':'Jack'}],
  [{'score':3, 'name':'Danielle'}]
]

I am trying to iterate through this list but can't figure out how to access the values.

for listing in my_list:
  print(listing['score'])

The above does not work. Which I understand as I seem to be working on a dictionary that is still inside the second list. However, I am having trouble finding out the correct way to do get access.

5 Answers

You can try this by matching exact the signature of the inner elements. This is called tuple unpacking

my_list = [
  [{'score':9, 'name':'Jack'}],
  [{'score':3, 'name':'Danielle'}]
]
for [listing] in my_list:
    print(listing['score'])
# 9
# 3

You are using the wrong syntax for python dictionaries.

Python dictionaries are declared between {...}.

Your list should look like:

my_list = [
  {'score':9, 'name':'Jack'},
  {'score':3, 'name':'Danielle'}
]

EDIT:
In your edit you have a list within a list. Try

for listing in my_list:
  print(listing[0]['score'])

What are you creating is a 2D List, you need Dictionaries inside that

my_list = [
  {'score':9, 'name':'Jack'},
  {'score':3, 'name':'Danielle'}
]
for listing in my_list:
  print(listing['score'])

You need 2 loops, one for the outer list, and one for the inner list:

my_list = [
     [{'score':9, 'name':'Jack'}],
     [{'score':3, 'name':'Danielle'}]
]

for sublist in my_list:
     for dct in sublist:
          print(dct['score'])
# 9
# 3

You can also use nested list comprehension:

print([dct['score'] for sublist in my_list for dct in sublist])
# [9, 3]

You need to create the items inside your list with {} rather than [].

my_list = [
  {'score':9, 'name':'Jack'},
  {'score':3, 'name':'Danielle'}
]

[] will create a list, while {} will create a dict.

Related