簡體   English   中英

元組到字典,其中第一個元組是鍵,第二個元組是對應的元素?

[英]Tuples to dictionary , where first tuple are keys and second tuple is corresponding elements?

需要一個函數,它接受兩個元組並返回一個字典,其中第一個元組的元素用作鍵,第二個元組的相應元素

例如,調用tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4))將返回{'a':1, 'b':2, 'c':3}

您可以將dictzip方法一起使用:

  • zip()將兩個或多個迭代合並為兩個元組。
  • dict()函數創建一個字典。
def tuples_to_dict(x,y):
    return dict(zip(x,y))

結果{'a': 4, 'b': 2, 'c': 3}

使用enumerate字典理解的其他方式:

def tuples_to_dict(x,y):
    return {x[i]:y[i] for i,_ in enumerate(x)}

如果您需要它不插入第二個“a”,則可以在插入值之前進行檢查,如果已經存在則不要這樣做:


def tuples_to_dict(first, second):
    out = {}
    for k, v in zip(first, second):
        if k not in out:
            out[k] = v
    return out

tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4))
{'a': 1, 'b': 2, 'c': 3}

暫無
暫無

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

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