簡體   English   中英

使用元組鍵從Dictionary [key1,key2]獲取第一個鍵的列表

[英]Get list of first keys from Dictionary[key1,key2] with tuple keys

如何從雙鍵字典中獲取第一把鍵的所有(唯一)值的列表?

是迭代鍵值然后應用np.unique()的唯一方法嗎?

key1=[]
for key in my_dictionary.keys():
    key1.append(key[0])

np.unique(key1)

假設您有一本帶有元組鍵的字典:

d = {('a', 'b'): 1, ('b', 'c'): 2, ('a', 'd'): 3, ('b', 'e'): 4}

您可以使用setmapoperator.itemgetter從元組鍵中提取一組第一批元素:

from operator import itemgetter

res = set(map(itemgetter(0), d))  # {'a', 'b'}

僅建議將NumPy庫和numpy.unique與NumPy數組或可以有效轉換為NumPy數組(例如數字列表)的Python對象一起使用。

您可以這樣做:

key1 = set([key[0] for key in my_dictionary])

正如@ Aran-Fey所建議的那樣,您還可以使用集合理解:

key1 = {key[0] for key in my_dictionary}

暫無
暫無

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

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