![](/img/trans.png)
[英]Filtering dictionary based on first key in a tuple key (key1, key2), where key1
[英]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}
您可以使用set
和map
和operator.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.