簡體   English   中英

將3元素元組的列表轉換為字典

[英]Converting List of 3 Element Tuple to Dictionary

如果我有兩個元組列表

tuple2list=[(4, 21), (5, 10), (3, 8), (6, 7)]

tuple3list=[(4, 180, 21), (5, 90, 10), (3, 270, 8), (6, 0, 7)]

如何將其轉換為字典,如下所示,

tuple2list2dict={4:21, 5:10, 3:8, 6:7}

tuple3list2dict={4: {180:21}, 5:{90:10}, 3:{270:8}, 6:{0:7}}

我知道如何為元組中的2個元素執行它,使用,

tuple2list2dict=dict((x[0], index) for index,x in enumerate(tuple2list))

但對於3個元素我有問題,嘗試下面的錯誤,

tuple3list2dict=dict((x[0], dict(x[1], index)) for index,x in enumerate(tuple3list))

如何重用上面的3元組元組代碼來創建字典?

任何指針都贊賞或指出我可以閱讀更多內容。 無法在互聯網上找到它。

在Python2.7或更高版本中,您可以使用dict理解:

In [100]: tuplelist = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]

In [101]: tuplelist2dict = {a:{b:c} for a,b,c in tuplelist}

In [102]: tuplelist2dict
Out[102]: {3: {270: 8}, 4: {0: 7}, 5: {90: 10}}

在Python2.6或更早版本中,等價物將是

In [26]: tuplelist2dict = dict((a,{b:c}) for a,b,c in tuplelist)

請注意,如果元組中的第一個值出現多次,(如上例所示),生成的tuplelist2dict只包含一個鍵值對 - 對應於具有共享鍵的最后一個元組。

這種情況很簡單,因為它與dict結構一致:

...位置參數必須是迭代器對象。 iterable中的每個項本身必須是一個只有兩個對象的迭代器。 每個項目的第一個對象成為新詞典中的一個鍵,第二個對象成為相應的值。

>>> t = [(4, 21), (5, 10), (3, 8), (4, 7)]
>>> dict(t)
{3: 8, 4: 7, 5: 10}

三重案例可以通過這種方式解決:

>>> t = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]
>>> dict([ (k, [v, w]) for k, v, w in t ])
{3: [270, 8], 4: [0, 7], 5: [90, 10]}

或者更一般:

>>> dict([ (k[0], k[1:]) for k in t ]) # hello car, hi cdr
{3: (270, 8), 4: (0, 7), 5: (90, 10)}

請注意您的代碼:

_3_tuplelist_to_dict = {4: {180:21}, 5:{90:10}, 3:{270:8}, 4:{0:7}}

實際上只是一個令人困惑的代表:

{3: {270: 8}, 4: {0: 7}, 5: {90: 10}}

嘗試:

>>> {4: {180:21}, 5:{90:10}, 3:{270:8}, 4:{0:7}} == \
    {3: {270: 8}, 4: {0: 7}, 5: {90: 10}}
True

使用Python 3,您可以使用dict理解:

>>> t = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]
>>> {key: values for key, *values in t}
{3: [270, 8], 4: [0, 7], 5: [90, 10]}

如果想要嵌套字典而不覆蓋字典,可以使用collections庫中的defaultdict

>>> from collections import defaultdict
>>> # Edited the list a bit to show when overrides
>>> tuple3list=[(4, 180, 21), (4, 90, 10), (3, 270, 8), (6, 0, 7)]
>>> tuple3dict = defaultdict(dict)
>>> for x, y, z in tuple3list:
...     tuple3dict[x][y] = z
... 
>>> print(tuple3dict)
defaultdict(<class 'dict'>, {4: {180: 21, 90: 10}, 3: {270: 8}, 6: {0: 7}})
>>> tuple3dict[4][90]
10

不幸的是,一行分配很棘手或不可能,因此我認為唯一有效的解決方案就是這樣。

暫無
暫無

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

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