简体   繁体   中英

How to create an arbitrary number of dictionaries/lists (with different names) in python?

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

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': {}}

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': []}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM