-1

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
  • 232,417
  • 55
  • 437
  • 487
Rolando
  • 51,528
  • 92
  • 250
  • 377

5 Answers5

5
>>> firstdict = {"somelist":[]}
>>> seconddict = {"attribute1": "value1", "attribute2": "value2"}
>>> firstdict["somelist"].append(seconddict)
>>> print firstdict["somelist"][0]['attribute1']
value1
jamylak
  • 120,885
  • 29
  • 225
  • 225
1

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

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
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
  • 124,516
  • 15
  • 228
  • 298
0
firstdict["somelist"][0]['attribute1']
NIlesh Sharma
  • 5,265
  • 6
  • 34
  • 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
blackfedora
  • 1,000
  • 9
  • 16