Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
SomeDutchGuy Avatar asked Nov 16 '25 09:11

SomeDutchGuy


2 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
like image 68
Ch3steR Avatar answered Nov 19 '25 00:11

Ch3steR


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'])
like image 30
Ruan Avatar answered Nov 18 '25 23:11

Ruan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!