2013-04-10 125 views
3

的字典如何轉換字典的名單看起來是這樣的:轉換詞典列表到元組

[{'id':2, 'risk':'a'}, 
{'id':1, 'risk':'a'}, 
{'id':32,'risk':'aa'}, 
{'id':2, 'risk':'aa'}, 
{'id':7, 'risk':'a'}, 
{'id':7, 'risk':'b'}] 

成元組的字典,這將是這樣排序後:

{1:('a',), 2:('a','aa'), 7:('a','b'), 32:('aa',)} 
+0

固定的單一元組,記住'(「A」)'實際上不是一個元組,這只是使用圓括號組字符串''a''。 – jamylak 2013-04-10 07:38:23

回答

3

可以使用defaultdict自動創建的元組,那麼就遍歷list_of_dicts

list_of_dicts = [{'id':2, 'risk':'a'}, 
{'id':1, 'risk':'a'}, 
{'id':32,'risk':'aa'}, 
{'id':2, 'risk':'aa'}, 
{'id':7, 'risk':'a'}, 
{'id':7, 'risk':'b'}] 

from collections import defaultdict 

dict_of_tuples = defaultdict(tuple) 

for dct in list_of_dicts: 
    dict_of_tuples[dct['id']] += (dct['risk'],) 

導致:如果你再想一個排序的字典

>>> dict_of_tuples 
defaultdict(<type 'tuple'>, {32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')}) 

>>> from collections import OrderedDict 
>>> OrderedDict(sorted(dict_of_tuples.items())) 
OrderedDict([(1, ('a',)), (2, ('a', 'aa')), (7, ('a', 'b')), (32, ('aa',))]) 
+0

即返回一個錯誤對我來說:回溯(最近最後一次通話): 文件 「Dict_to_Tuples.py」,13號線,在 dict_of_tuples [DCT [ '身份證'] + = DCT [ '風險'] 類型錯誤:只能連接元組(不是「str」)到元組 – user1793317 2013-04-10 05:12:38

+0

請注意,OrderedDict只在2.7,OP在使用2.6 – 2013-04-10 05:14:07

+0

@ user1793317你忘記把它變成一個元組('dict ['risk'], )' – 2013-04-10 05:14:45

0

更長的方式這樣做。還不如利落的AGF的解決方案,但它的工作原理

new_dict = {} 
for x in my_dict_list: 
    m = new_dict.get(x['id'],()) 
    m += (x['risk'],) 
    new_dict[x['id']] = m 

輸入

my_dict_list = [{'id':2, 'risk':'a'}, 
       {'id':1, 'risk':'a'}, 
       {'id':32,'risk':'aa'}, 
       {'id':2, 'risk':'aa'}, 
       {'id':7, 'risk':'a'}, 
       {'id':7, 'risk':'b'}] 

輸出

>>> new_dict 
{32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')} 
+1

''你可以改變它來創建元組,然後你不需要第二個'for'循環。 'new_dict [x ['id']] =(x ['risk'],)'in'if',in'else','new_dict [x ['id']] + =(x [風險'],)' – 2013-04-10 05:21:18

+0

感謝提示 – RedBaron 2013-04-10 05:23:16

2

dict.setdefault方法使這類問題的短期工作:

>>> lod = [{'id':2, 'risk':'a'}, 
      {'id':1, 'risk':'a'}, 
      {'id':32,'risk':'aa'}, 
      {'id':2, 'risk':'aa'}, 
      {'id':7, 'risk':'a'}, 
      {'id':7, 'risk':'b'}] 
>>> dot = {} 
>>> for d in lod: 
     idnum, risk = d['id'], d['risk'] 
     dot.setdefault(idnum, []).append(risk) 

>>> dot 
{32: ['aa'], 1: ['a'], 2: ['a', 'aa'], 7: ['a', 'b']} 

您也可以使用collections.defaultdict創建相同的效果,但不會創建常規字典,它需要了解工廠函數和零參數構造函數。

+1

+1以避免元組的連接(n^2)。如果真的需要它們,它們總是可以被轉換 – jamylak 2013-04-10 05:42:01

1

通常人們會忘記在類似的情況下使用dict.get方法。因此,與基本的Python功能:

list_of_dicts = [{'id':2, 'risk':'a'}, 
    {'id':1, 'risk':'a'}, 
    {'id':32,'risk':'aa'}, 
    {'id':2, 'risk':'aa'}, 
    {'id':7, 'risk':'a'}, 
    {'id':7, 'risk':'b'}] 

final_dict = {} 

for item in list_of_dicts: 
    final_dict[item['id']] = final_dict.get(item['id'], tuple()) + (item['risk'],) 


>> {1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b'), 32: ('aa',)}