How to get data from list with dictionary

256 views Asked by At

Hello I have a python variable with List plus 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 have tried everything But I couldn't get 'addr' extracted.

Help Please.

6

There are 6 answers

1
Hackaholic On BEST ANSWER

try this:

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

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

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

Read about python data structure here Data structure

2
heemayl On

You can just 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'
1
BMW On

print list by its key

print(b[0]['addr'])
1
Morgan G On

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

1
Anton Protopopov On

You could use get method of dict:

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

From docs:

get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

0
Shanu Pandit On

You may use get method of dict, which works on the key, and provide the corresponding value. b[0].get('addr')