0

I want to accomplish the following:

vname = [ 'name1', 'name2']

for i in len(vname):
  vname[i] = {} 
  vname[i]['key1'] = 4*i

I expect to create two dictionaries name1 and name2 such that

name1['key1'] = 0
name2['key1'] = 4
2
  • your list contains strings not dictionaries, when you do vname[i] = {} you replace the string with a dictionary so the variables name1 and name2 never exist, also I assume you mean to use 4*i instead of 4*1 since the latter is just 4. Commented Jun 6, 2016 at 15:05
  • corrected the code to 4*i Commented Jun 6, 2016 at 15:08

2 Answers 2

1

I'd use a nested dictionary instead, generating values with the help of enumerate():

>>> {key: {'key1': index * 4} for index, key in enumerate(vname)}
{'name2': {'key1': 4}, 'name1': {'key1': 0}}
Sign up to request clarification or add additional context in comments.

Comments

0

In order to dynamically create variables of a certain name, you could add them to the global namespace:

>>> vname = [ 'name1', 'name2']
>>> for i in range(len(vname)):
...     globals()[vname[i]] = {}
...     globals()[vname[i]]['key1'] = 4*i
... 
>>> name1
{'key1': 0}
>>> name2
{'key1': 4}

However, I have never encountered a situation where this was useful or necessary. If you are trying to sth. like this, you are very likely better off with a different (and better behaved) data structure like the nested dict suggested by @alexce.

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.