[英]python Get the unique values from a dictionary
我想從我的字典中獲取唯一值。
輸入:
{320: [167], 316: [0], 319: [167], 401: [167], 319: [168], 380: [167], 265: [166]}
期望的輸出:
[167,0,168,166]
我的代碼:
unique_values = sorted(set(pff_dict.itervalues()))
但是我收到了這個錯誤: TypeError: unhashable type: 'list'
列表不符合候選集內容,因為它們不可用 。
在調用set
之前,您可以使用itertoos.chain.from_iterable
將項合並到一個容器中:
from itertools import chain
unique_values = sorted(set(chain.from_iterable(pff_dict.itervalues())))
請注意,使用itertools
不違反您的選擇dict.itervalues
在dict.values
為解纏/鏈接是懶洋洋地完成。
目前尚不清楚為什么要將單項列表映射為值,但您可以使用列表推導來提取元素。
foobar = {320: [167], 316: [0], 319: [167], 401: [167], 319: [168], 380: [167], 265: [166]}
print list(set([x[0] for x in foobar.values()]))
如果您通過直接映射到值開始,代碼可以更簡單。
foobar = {320: 167, 316: 0, 319: 167, 401: 167, 319: 168, 380: 167, 265: 166}
print list(set(foobar.values()))
set
期望元素不是列表列表,所以你必須使用list comprehension
創建元素list comprehension
In [34]: sorted(set([i[0] for i in d.values()]))
Out[34]: [0, 166, 167, 168]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.