Reputation: 45
How do I add key: value
pairs to a dictionary within a dictionary in Python?
I need to take an input of a dictionary and sort the results by the type of the key:
new_d = {'int':{}, 'float':{}, 'str':{}}
temp = {}
for key in d:
temp[key] = d[key]
print temp
if type(key) == str:
new_d['str'] = temp
temp.clear()
elif type(key) == int:
print 'int'
temp.clear()
elif type(key) == float:
print 'float'
temp.clear()
This is what I have and nothing is writing to the new_d
dictionary.
Output should look like this
>>> new_d = type_subdicts({1: 'hi', 3.0: '5', 'hi': 5, 'hello': 10})
>>> new_d[int]
{1: 'hi'}
>>> new_d[float]
{3.0: '5'}
>>> new_d[str] == {'hi': 5, 'hello': 10}
True
"""
Upvotes: 0
Views: 204
Reputation: 49330
You don't need a temporary dictionary for that. You can use the types directly as keys, too.
d = {1:'a', 'c':[5], 1.1:3}
result = {int:{}, float:{}, str:{}}
for k in d:
result[type(k)][k] = d[k]
Result:
>>> result
{<class 'float'>: {1.1: 3}, <class 'str'>: {'c': [5]}, <class 'int'>: {1: 'a'}}
>>> result[float]
{1.1: 3}
If you want, you can use collections.defaultdict
to automatically add keys of the necessary type if they don't yet exist, instead of hard-coding them:
import collections
d = {1:'a', 'c':[5], 1.1:3}
result = collections.defaultdict(dict)
for k in d:
result[type(k)][k] = d[k]
Result:
>>> result
defaultdict(<class 'dict'>, {<class 'float'>: {1.1: 3}, <class 'str'>: {'c': [5]}, <class 'int'>: {1: 'a'}})
>>> result[float]
{1.1: 3}
Upvotes: 4