5

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.

Raja G
  • 5,973
  • 14
  • 49
  • 82

6 Answers6

3

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'
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • This is different from what I have asked. This is extracting from a simple dictionary but what I have asked have a list too, – Raja G Feb 08 '16 at 06:25
  • 1
    @Raja Ok..no problem..the notion is same..you just need to add the list index..thats it..check edit :) – heemayl Feb 08 '16 at 06:31
3

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

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
3

print list by its key

print(b[0]['addr'])
BMW
  • 42,880
  • 12
  • 99
  • 116
3

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

The6thSense
  • 8,103
  • 8
  • 31
  • 65
Morgan G
  • 3,089
  • 4
  • 18
  • 26
3

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.

Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
1

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

Shanu Pandit
  • 122
  • 1
  • 10