1

i'd like to know how to populate an empty dictionary with other dictionaries in the manner below:

newdict = {}

dict1 = {"key1": "value1"}
dict2 = {"key2": "value2"}
dict3 = {"key3": "value3", "key4": "value4"}

dicts_to_use = [dict1, dict3]

so a list is used to specify which ones to include, and newdict in this case should be populated such that it would show:

{'dict1': {'key1': 'value1'}, 'dict3': {'key3': 'value3', 'key4': 'value4'}}

im running into trouble referring to the dictionaries in the list and crossing across string/dictionary types

laszlopanaflex
  • 1,836
  • 3
  • 23
  • 34
  • 8
    It seems like `dicts_to_use` could just as easily be a dict -- i.e. `dicts_to_use = {'dict1': dict1, 'dict3': dict3}` -- And then you're done because that's what you're asking for ;-) – mgilson Mar 09 '17 at 01:04

2 Answers2

2

You can't do this. The reason you can't is because there's no reliable way to get the string 'dict1' from the object dict1.

Now, I understand your variable names in the actual code are probably different than this simplified example, yet the same issue that will still trip you up: in general, an object can't tell you what names it is bound to. It might be bound to multiple names, or none at all.

You'll have to rethink your approach to variable names.

Community
  • 1
  • 1
wim
  • 338,267
  • 99
  • 616
  • 750
-5

Use eval. (Note that I changed dicts_to_use to include the names of the dicts, and not the dicts themselves...)

>>> newdict = {}
>>> 
>>> dict1 = {"key1": "value1"}
>>> dict2 = {"key2": "value2"}
>>> dict3 = {"key3": "value3", "key4": "value4"}
>>> 
>>> dicts_to_use = ["dict1", "dict3"]
>>> for d in dicts_to_use:
...     newdict[d] = eval(d)
... 
>>> newdict
{'dict1': {'key1': 'value1'}, 'dict3': {'key3': 'value3', 'key4': 'value4'}}
>>> 
Alex L
  • 1,114
  • 8
  • 11