Python Accessing Values ​​in a Dictionary List

Let's say I have a list of dictionaries with names and ages and other information, for example:

thisismylist= [ {'Name': 'Albert' , 'Age': 16}, {'Name': 'Suzy', 'Age': 17}, {'Name': 'Johnny', 'Age': 13} ] 

How can I print the following using a for loop:

 Albert Suzy Johnny 

I just tilt my head around this idea ...

+6
source share
6 answers

If you are simply looking for values ​​associated with "Name", your code should look like this:

 for d in thisismylist: print d['Name'] 
+12
source

If you need a list of these values:

 >>> [d['Name'] for d in thisismylist] ['Albert', 'Suzy', 'Johnny'] 

The same method, you can get a tuple of data:

 >>> [(d['Name'],d['Age']) for d in thisismylist] [('Albert', 16), ('Suzy', 17), ('Johnny', 13)] 

Or, flip the dicts list into one key, a dictionary of a pair of values:

 >>> {d['Name']:d['Age'] for d in thisismylist} {'Johnny': 13, 'Albert': 16, 'Suzy': 17} 

So, the same method, the way to print them:

 >>> print '\n'.join(d['Name'] for d in thisismylist) Albert Suzy Johnny 

And you can print it sorted if you want:

 >>> print '\n'.join(sorted(d['Name'] for d in thisismylist)) Albert Johnny Suzy 

Or, sort them by age, smoothing the list:

 >>> for name, age in sorted([(d['Name'],d['Age']) for d in thisismylist],key=lambda t:t[1]): ... print '{}: {}'.format(name,age) ... Johnny: 13 Albert: 16 Suzy: 17 
+5
source

It looks like you need to go through the Python flow control documentation . Basically, you just iterate over all the elements in your list, and then for each of these elements (in this case, dictionaries) you can access any values ​​you want. For example, the code below will display each value in each dictionary within a list.

 for d in my_list: for key in d: print d[key] 

Please note that this does not print keys, but only values. To print the keys, make your print statement print key, d[key] . It's simple!

But really, read the flow control documentation; it is very nice.

+3
source

The following code should work fine.

 for var in thisismylist: print var['Name'] 
+1
source

You can project the Name attribute from each element in the list and append the results to newline characters:

 >>> print '\n'.join(x['Name'] for x in thisismylist) Albert Suzy Johnny 

Edit

It took me a few minutes, but I remembered another interesting way to do this. You can use a combination of itertools and operator to do this. You can see it on repl.it too .

 >>> from itertools import imap >>> from operator import itemgetter >>> print '\n'.join(imap(itemgetter('Name'), thisismylist)) Albert Suzy Johnny 

You should probably use the vanilla for loop anyway, but I decided some other options were ok.

0
source

A shorthand way to do this without importing libraries:

 print('\n'.join([e["Name"] for e in thisismylist])) 
0
source

Source: https://habr.com/ru/post/947343/


All Articles