Building and accessing an array of dictionaries

S

Sam

I would like to build an array of dictionaries. Most of the dictionary example on the net are for single dictionary.

dict = {'a':'a','b':'b','c':'c'}
dict2 = {'a':'a','b':'b','c':'c'}
dict3 = {'a':'a','b':'b','c':'c'}

arr = (dict,dict2,dict3)

What is the syntax to access the value of dict3->'a'?

Thank you.
 
C

Chris Angelico

I would like to build an array of dictionaries. Most of the dictionary example on the net are for single dictionary.

dict = {'a':'a','b':'b','c':'c'}
dict2 = {'a':'a','b':'b','c':'c'}
dict3 = {'a':'a','b':'b','c':'c'}

arr = (dict,dict2,dict3)

What is the syntax to access the value of dict3->'a'?

Technically, that's a tuple of dictionaries, and you may want to use a
list instead:

lst = [dict, dict2, dict3]

Like any other list or tuple, you can reference them by their indices:

lst[2] is dict3

lst[2]['a'] is dict3['a']

Hope that helps!

ChrisA
 
J

Jussi Piitulainen

Sam said:
I would like to build an array of dictionaries. Most of the
dictionary example on the net are for single dictionary.

dict = {'a':'a','b':'b','c':'c'}
dict2 = {'a':'a','b':'b','c':'c'}
dict3 = {'a':'a','b':'b','c':'c'}

arr = (dict,dict2,dict3)

What is the syntax to access the value of dict3->'a'?

This isn't a special case.

arr[2] to get the dictionary
arr[2]['a'] to get the value in the dictionary

'a' in arr[2] to find if there is such a key

arr[2].get('a') to get the value or None if the key isn't there
arr[2].get('a', 'd') to get a value even if the key isn't there

help(dict.get)

for key in arr[2]:
# to iterate over the keys

The exact same mechanisms are used no matter where you get the
dictionary from.
 
G

Grant Edwards

For the benefit of lurkers, newbies or whatever it's the commas that
make the tuple, not the brackets.

In _that_ example, yes. There are other cases where it's the
brackets (sort of):

foo('a','b','c') # three separate string objects are passed

foo(('a','b','c')) # a single tuple object is passed
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top