簡體   English   中英

用序列中的列表值創建字典的最簡潔(最Pythonic)方法是什么?

[英]What's the cleanest (most Pythonic) way of creating a dictionary with list values from a sequence?

我有一個看起來像這樣的集合:

stuff = [('key1', 1), ('key2', 2), ('key3', 3), 
         ('key1', 11), ('key2', 22), ('key3', 33),
         ('key1', 111), ('key2', 222), ('key3', 333),
         ]
# Note: values aren't actually that nice. That would make this easy.

我想把它變成這樣的字典:

dict_stuff = {'key1': [1, 11, 111],
              'key2': [2, 22, 222],
              'key3': [3, 33, 333],
              }

轉換此數據的最佳方法是什么? 我想到的第一種方法是:

dict_stuff = {}
for k,v in stuff:
    dict[k] = dict.get(k, [])
    dict[k].append(v)

這是最干凈的方法嗎?

您可以像這樣使用dict.setdefault

dict_stuff = {}
for key, value in stuff:
    dict_stuff.setdefault(key, []).append(value)

它說,如果字典中不存在該key ,則使用第二個參數作為其默認值,否則返回與該key對應的實際值。

我們還有一個內置的dict類,可幫助您處理類似情況的稱為collections.defaultdict

from collections import defaultdict
dict_stuff = defaultdict(list)
for key, value in stuff:
    dict_stuff[key].append(value)

在這里,如果keydefaultdict對象中不存在,則傳遞給defaultdict構造函數的工廠函數將被調用以創建value對象。

collections庫中有defaultdict

>>> from collections import defaultdict
>>> dict_stuff = defaultdict(list) # this will make the value for new keys become default to an empty list
>>> stuff = [('key1', 1), ('key2', 2), ('key3', 3), 
...          ('key1', 11), ('key2', 22), ('key3', 33),
...          ('key1', 111), ('key2', 222), ('key3', 333),
...          ]
>>> 
>>> for k, v in stuff:
...     dict_stuff[k].append(v)
... 
>>> dict_stuff
defaultdict(<type 'list'>, {'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]})
stuff_dict = {}
for k, v in stuff:
    if stuff_dict.has_key(k):
        stuff_dict[k].append(v)
    else:
        stuff_dict[k] = [v]


print stuff_dict
{'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM