[英]Adding key:value pair in a dictionary within a dictionary
如何在Python字典中的字典中添加key: value
對? 我需要輸入字典並按鍵的類型對結果進行排序:
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
"""
您不需要為此使用臨時字典。 您也可以直接將類型用作鍵。
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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.