How to get data from a dictionary list

Hello, I have a python variable with a list of words and a dictionary

>>> print (b[0]) {'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'} ----------------------------------------------------------------------- >>> print (b) [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] >>> 

I tried everything, but I could not extract the 'addr' .

Help me please.

+5
source share
6 answers

try the following:

 print (b[0]['addr']) 

print (b [0]) gives the dictionary, in the dictionary you can get the value by its key, for example dict [key] => returns its associated value.

so print(b[0]['addr']) will give you the value addr

Read about python data structure here data structure

+3
source

You can simply use b[0]['addr'] :

 >>> b = [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] >>> b[0]['addr'] '127.0.0.1' 
+3
source

print the list by its key

 print(b[0]['addr']) 
+3
source

You can just use print(b[0]['addr'])

+3
source

You can use the get dict method:

 >>> b[0].get('addr') '127.0.0.1' 

From docs :

get (key [, default])
Return the value for the key if the key is in the dictionary, otherwise by default. If no default value is specified, it defaults to None , so this method never raises a KeyError value.

+3
source

You can use the get method of the dict method, which works with the key and provides the corresponding value. b[0].get('addr')

+1
source

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


All Articles