0

I have a list of strings:

list1 = ['array1', 'array2', 'array3']

whose elements I would like to use as names of other lists, like (as conceptual example):

list1[0] = [1, 2, 3]

I know this assignation does not make any sense, but it is only to show what I need. I have looked for this a lot but didn't find a handy example. If I understood properly, this is not the right way to do it, and better is to use dictionaries. But, I never used dictionaries yet, so I would need some examples.

3 Answers 3

1
aDict = { name: 42 for name in list1 }

This gives you:

{'array3': 42, 'array2': 42, 'array1': 42}

If you wanted it ordered:

from collections import OrderedDict
aDict = OrderedDict((name, 42) for name in list1)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. If I try aDict = { name: [] for name in list1 }, when I print adict the order of the elements is not the same as in list1, why?
Because dictionaries are not ordered. They use hash tables to make lookups by name fast instead. If you want to preserve order there is an OrderedDict subclass, but this is rarely necessary.
Ok, and how would be OrderedDict used in this case, if I want to print aDict with the original order?
@Py-ser: I updated my answer to include OrderedDict.
1

Use a dictionary:

list1 = {'array1': [0, 1, 2], 'array2': [0, 3], 'array3': [1]}

and then access it like this:

list1['array1'] # output is [0, 1, 2]

To dynamically populate your dictionary:

list1 = {'array1': []}
list1['array1'].append(1)

4 Comments

I don't know the content of the lists when I define my dictionary!
@Py-ser I have added another code snippet. Treat everything that you dereference from the dictionary by key as a list because that's what it is in your case.
Thanks! So why can't I just print array1 ?
@Py-ser Because it's contained in the dictionary, so you have to do print list1['array1']
1

You can do What you want with exec like this :

list1 = ['array1', 'array2', 'array3']
x=list1[1]    
exec("%s = %d" % (x,2))
print array2

so result is : 2

But never use exec when you can use something much safer like dictionary, it can be dangerous !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.