0

Is it possible to reference a dictionary or list in Python, using a string as it's name when referenced?

for example, would it be possible to make "print(reference[1])" in this code actually work and reference the dictionaries?

sampledict = {1:'valueA',2:'valueB'}
sampledict2 = {1:'valueC',2:'valueD'}

for x in range(1,3):
    reference = 'sampledict' + str(x)
    print(reference[1])

I apologize if the question is basic, as I am somewhat new to python.

PaperBox
  • 3
  • 1
  • I can think of two ways you can try. Firstly, storing the dictionaries in a list and referencing them by index. Secondly, using `eval("sampledict" + str(x))` should do what you want, but I'm not sure if that's really the most appropriate way. – Misha Melnyk Apr 14 '20 at 11:02
  • Is it `sampledict` and `sampeldict2` or did you mean `sampledict1` and `sampeldict2`? – 0buz Apr 14 '20 at 11:10
  • yes, i did mean sampledict1 and sampledict2, sorry, it was a very basic example. I should definitely try indexing them in a list, I had not thought of that. – PaperBox Apr 14 '20 at 11:20

2 Answers2

1

In this particular example I would strongly suggest you'd rather use a list to store your "sampledict"s and reference them by index or store them in a dict and reference them by keys.

If you must, you access the local variable dictionary through locals:

reference = 'sampledict1'
print(locals().get(reference))
0

You can change your codes to below:

sampledict = {1:'valueA', 2:'valueB'}
sampledict2 = {1:'valueC', 2:'valueD'}

reference = [eval(i) for i in globals() if i.startswith("sampledict")]
print(reference[0])
print(reference[1])

Output:

{1: 'valueA', 2: 'valueB'}
{1: 'valueC', 2: 'valueD'}

If you wanna print the names of the dictionaries just put the i out from eval function.

dildeolupbiten
  • 1,314
  • 1
  • 15
  • 27