[英]How convert list of dictionaries to a dictionary of dictionaries in Python
[英]How can make all dictionaries inside list of dictionaries Default in Python
假設我有這樣的詞典列表
dlist = [d1, d2, d3, d4]
現在d1 inturn是字典的字典
d1 = {'dd1':{'a':2. 'ddd1':'moredict'}}
而里面可以有更多的詞典
是否有單行功能可以將所有這些詞典轉換為聾人。
我希望如果在任何一個子dict中不存在某些key
,那么它就不會出現關鍵錯誤。
編輯:
#something like this , but i was looking for something buildin
def convert_dict(dictionary):
for key, value in dictionary.iteritems():
if isinstance(value, dict):
dictionary[key] = defaultdict(list, value)
convert_dict(value)
我希望如果在任何一個子dict中不存在某些鍵,那么它就不會出現關鍵錯誤。
設置默認值是一個選項,或者只使用get
:
>>> d = {'key': 1}
>>> d['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> d.get('foo')
如果一個鍵不存在, get
將返回None
,而不是引發KeyError
。 您可以通過傳入它來返回除None之外的默認值:
>>> d.get('foo',{})
{}
正如dbaupp已經說過的那樣,編寫遞歸函數會不會更好? 因為你的詞典可以嵌套,所以我不認為有一種“漂亮”的方法來處理它。
def dict_to_ddict(d, defaultfunction):
'''Convert (nested) dict to defaultdict'''
ddict = defaultdict(defaultfunction)
for k, v in d.iteritems():
if isinstance(v, dict):
ddict[k] = dict_to_ddict(v, defaultfunction)
else:
ddict[k] = v
return ddict
你可以使它更緊湊,但這不會使它更容易閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.