使用元组键从Dictionary [key1,key2]获取第一个键的列表

问题描述 投票:1回答:2

如何从双键字典中获取第一个键的所有(唯一)值的列表?

迭代键值然后应用np.unique()唯一的方法?

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

np.unique(key1)
python dictionary set
2个回答
1
投票

你可以这样做:

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

正如@ Aran-Fey建议您也可以使用集合理解:

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

3
投票

假设你有一个包含元组键的字典:

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数组或Python对象,可以有效地转换为NumPy数组,例如数字列表。

© www.soinside.com 2019 - 2024. All rights reserved.