Python Forum
How to get python to select a dictionary. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to get python to select a dictionary. (/thread-10690.html)



How to get python to select a dictionary. - jarrod0987 - May-31-2018

I'm not even sure how to word my question. I know exactly what I want to do but I don't know how to ask it so I will try an example.

Suppose I have multiple dictionaries with the same keys but different values. I want to be able to programmatic change the name of the dictionary that is being searched. What I DON'T want to have to do is type something like look in this one, then this one, then this one, then this one and have to type the name into the code every time. What I want to do is something more like name each dictionary with a similar name but perhaps a single letter different. Such as this:
dict01 and dict02 are seperate dictionary files. I want to look for the key called 'myKey'.

So I have a list called dictList.
['dict01', 'dict02']

maybe I can do something like:
for x in dictList:
print (x['myKey'])
Can I even do something like this?


RE: How to get python to select a dictionary. - wavic - Jun-01-2018

You can. Have you tried it?
>>> d_a = {'myKey': 'a'}
>>> d_b = {'myKey': 'b'}
>>> for d in [d_a, d_b]:
...     print(d['myKey'])
... 
a
b