0

Assume I have a dict:

firstdict = {"somelist":[]}

I have another dict:

  seconddict = {"attribute1": "value1", "attribute2": "value2"}

After appending the dictionary

firstdict["somelist"].append(seconddict)

I want to print the "attribute1" value. Though the following statement is not working:

print firstdict["somelist"][0].attribute1

How to I print/access the value of attribute1?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Rolando
  • 58,640
  • 98
  • 266
  • 407

5 Answers5

5
>>> firstdict = {"somelist":[]}
>>> seconddict = {"attribute1": "value1", "attribute2": "value2"}
>>> firstdict["somelist"].append(seconddict)
>>> print firstdict["somelist"][0]['attribute1']
value1
jamylak
  • 128,818
  • 30
  • 231
  • 230
1

it's firstdict["somelist"][0]['attribute1']

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Python is not JavaScript; "attribute1" is no attribute, it is the key in the dictionary. To access the corresponding value, you use the [] indexing operator, just like you did with firstdict:

subdict = firstdict["somelist"][0]
print subdict["attribute1"]

or, simply:

print firstdict["somelist"][0]["attribute1"]
user4815162342
  • 141,790
  • 18
  • 296
  • 355
0
firstdict["somelist"][0]['attribute1']
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53
0

It seems weird to be storing dictionaries inside of a list inside of a dictionary. If you're using this to collect values from multiple dictionaries checkout this thread.

You might also consider nesting dictionaries:

>>>seconddict = {"key1": "value1", "key2": "value2"}
>>>firstdict = {'dict 1': seconddict}
>>> firstdict['dict 1']['key1']
'value1'
Community
  • 1
  • 1
Ian Burnette
  • 1,020
  • 10
  • 16