0

I'm trying to create #arb dictionaries like this:(arb = 2 or 4 or some number)

for n in xrange(0, arb):
    dictn = {}

However I realize that python doesn't take variables in the left side of equations.. So I'm confused. How can I have #arb dictionaries or lists with different names? like list1 through listn or dict1 through dictn.

I know this might sound stupid but I'm not good at program and terribly confused. Any suggestions would help, thanks

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
LilMuji
  • 57
  • 1
  • 1
  • 11

2 Answers2

2

It doesn't really make sense to attempt to create variables like that. If you have a need to dynamically create multiple dictionaries or lists in one go, you should put them in a container. A list is fine for that, or if you have an idea for keys, then why not a dict?

Example:

>>> arb = 4
>>> dicts = [{} for _ in range(arb)]
>>> print(dicts)
[{}, {}, {}, {}]

Or a dictionary of dicts:

>>> arb = 4
>>> dicts = {"dict_{}".format(i): {} for i in range(arb)}
>>> print(dicts)
{'dict_0': {}, 'dict_1': {}, 'dict_2': {}, 'dict_3': {}}
msvalkon
  • 11,887
  • 2
  • 42
  • 38
  • I'm not sure if I could make this clear, but after creating the dicts I need to assign different values to them, say I need `line n` of a file to be the key of `distn`, thats why I'm trying naming them in such a vague way – LilMuji Jul 02 '14 at 05:58
  • @LilMuji I understand, are you having some issues on how to do that? – msvalkon Jul 02 '14 at 07:36
  • I got it.. The whole idea about dictionary still confuses me a lot. Thanks for helping! – LilMuji Jul 03 '14 at 06:32
0

Create a dict container wich each key is the name's var. Try this

container_dict = {}
arb= 4
for n in xrange(0, arb):
    #for dicts
    container_dict["dict%i" % n] = {}
    #for lists
    container_dict["list%i" % n] = []

%i will interpolate the index, so keys will be numered from 0 to arb-1

>>> container_dict
{'dict1': {}, 'dict0': {}, 'dict3': {}, 'dict2': {}, 'list1': [], 'list0': [], 'list3': [], 'list2': []}
xecgr
  • 5,095
  • 3
  • 19
  • 28