Given:
dict = {}
I have an API call that returned a dictionary for a key:
key = {'k':'v', 'i':'v2'}
value = {'Medium': 1, 'High':2}
Now what I want is to add two dictionaries to dict
— something like this:
dict = { {'k':'v', 'i':'v2'} : {'Medium': 1, 'High':2}}
Is this possible? If so how to do it?
Edit: Looks like this doesn't work - thanks guys.
CodePudding user response:
You could do the following, or a hashed equivalent of the following, but it would be horribly fragile and a terrible idea:
#!/usr/bin/env python
import json
d = {}
k = {'k':'v', 'i':'v2'}
v = {'Medium': 1, 'High':2}
d[json.dumps(k)] = v
print(d)
If the JSON encoding of k
changes in any way, the data may not be retrievable from d
without a lot of expensive work.
Suggestion: Ask what it is you are really trying to do. There are probably a number of better ways to structure your data if you are trying to do this.
CodePudding user response:
Your key can't be a dictionary, but it could be a string, and my_dict is a better name:
my_dict = {"{'k':'v', 'i':'v2'}": {'Medium': 1, 'High': 2}}
and you could potentially parse that string for use later.
CodePudding user response:
You can't use a dictonary as a key, because dictonaries aren't hashable. I also suspect what you really want is completely different (more context needed). Regardless, strictly on the topic of using data structures as keys:
The closest, most reasonable solution would be using a paired tuple as a key. Usually you should do this when various bits of information make up a fixed, static, unique key.
For example:
dict_as_tuple_key = tuple({'k':'v', 'i':'v2'}.items())
result = { dict_as_tuple_key : {'Medium': 1, 'High':2}}
print(result)
Will give:
{(('k', 'v'), ('i', 'v2')): {'Medium': 1, 'High':2}}
Other answers mention dumping the dict into a json string. Don't do that, it's tedious and less reliable.
CodePudding user response:
You could most likely do this by defining a dictionary item normally in the dictionary dict
dict[key] = value
Hopefully this was helpful.