簡體   English   中英

將list = {“ xy”,“ wz”,“ ab”}轉換為dict = {x:y。 w:z,a:b}

[英]convert list = {“x-y”, “w-z”, “a-b”} into dict={x:y. w:z,a:b}

我已經搜索了很多有關如何將列表轉換成字典的方法,並找到了解決方案,但是沒有一個給出解決方案。

我有一個清單

LIST = {"x-y", "w-z","a-b"}

現在我想將其轉換成應該像這樣的字典

DICT = {'x':'y', 'w':'z', 'a':'b'}
input = {"x-y", "w-z","a-b"} 
output = dict(x.split('-', 1) for x in input)
d = {x.split('-')[0]: x.split('-')[1] for x in LIST}

使用dict

例如:

l = {"x-y", "w-z","a-b"}
print( dict([i.split("-") for i in l]) )

輸出:

{'a': 'b', 'x': 'y', 'w': 'z'}

注意: lset而不是列表

面對此類問題時,最好仔細考慮一些事情。

什么是字典?

從概念上講,字典是鍵值存儲,這意味着字典中的每個元素都是一對(key, value) 我們可以使用d[key] = value將值分配給字典,並可以使用d[key]檢索值。

現在我們知道了如何將值放入字典中。

輸入數據的格式是什么? 以及我需要做什么來轉換我的輸入數據?

或者輸入格式為<key>-<value> ,這意味着我們可以使用split來提取鍵和值。

>>> "x-y".split("-")
['x', 'y']

這使我們能夠做到這一點:

DICT = {}
for element in LIST:
    parts = element.split("-")

    if len(parts) != 2:
          # handle this case? (see below)
          ...

    (key, value) = (parts[0], parts[1])
    DICT[key] = value

我該如何處理錯誤?

我的輸入格式可以包含xya 這是什么? 這是(xy,a)還是(x,ya) 還是非法? 我該如何處理- 我該如何處理,如果沒有-它嗎?

>>> dict(x.split('-', 1) for x in ["a"])

如果使用這種方法,將引發您可能要處理的異常:

>>> dict(x.split('-', 1) for x in ["a"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

dict(x.split('-', 1) for x in僅適用於格式正確的輸入。

還有其他構建詞典的方法嗎?

仔細閱讀文檔,您會發現dict包含2個元組的列表。 這意味着您可以執行以下操作:

>>> dict([('a','b'),('c','d')])
{'a': 'b', 'c': 'd'}
d = {}                //simple dictionary declaration
for i in LIST:        // for loop to iterate and access each element of LIST
    d[i[0]] = i[2]    // this will use 1st letter of each word as key and 3rd letter as value of dictionary

暫無
暫無

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

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