2015-11-20 215 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}