2015-11-20 214 views
0

如何将key: value对添加到Python中的字典中的字典中? 我需要的密钥类型采取词典的输入和排序结果:在字典中的词典中添加键值对:

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() 

这是我并没有什么写new_d字典。

输出应该是这样的

>>> 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 
""" 
+0

你想让你的输出看起来像什么? – IanAuld

+0

这里'd'是什么可以让您更清楚地知道给定输入的输出 – The6thSense

+1

在第一个代码块中,'new_d'具有字符串键。在第二个代码块中,它具有类型键。 – TigerhawkT3

回答

4

你并不需要一个临时的字典做到这一点。您也可以直接将这些类型用作键。

d = {1:'a', 'c':[5], 1.1:3} 
result = {int:{}, float:{}, str:{}} 
for k in d: 
    result[type(k)][k] = d[k] 

结果:

>>> result 
{<class 'float'>: {1.1: 3}, <class 'str'>: {'c': [5]}, <class 'int'>: {1: 'a'}} 
>>> result[float] 
{1.1: 3} 

如果你愿意,你可以使用collections.defaultdict自动添加必要的类型的钥匙,如果他们不存在,而不是硬编码他们:

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 
defaultdict(<class 'dict'>, {<class 'float'>: {1.1: 3}, <class 'str'>: {'c': [5]}, <class 'int'>: {1: 'a'}}) 
>>> result[float] 
{1.1: 3}