[英]How to compare differently nested dictionaries and lists in Python and find intersection?
我現在有兩個(或多或少復雜)列表/字典。 第一個包含圖像名稱和十六進制圖像像素顏色。 所以看起來像這樣:
{
0: {'hex': ['#c3d6db', '#c7ccc0', '#9a8f6a', '#8a8e3e'], 'filename': 'imag0'},
1: {'hex': ['#705b3c', '#6a5639', '#442f1e', '#4a3d28'], 'filename': 'img-xyz'},
…
}
因此,在這種情況下,我將擁有2張2 x 2像素的圖片。
第二個字典包含許多十六進制值作為鍵,並包含一個id作為值。 看起來像:
{'#b0a7aa': '9976', '#595f5b': '19367', '#9a8f6a': '24095'…}
現在,我想做的是查看圖像(第一個列表)中是否有與第二個列表之一匹配的顏色值。 如果是這樣,那么我想知道第一個列表中的文件名以及第二個列表中匹配鍵的值,id。
我怎樣才能做到這一點?
使用字典視圖對象在hex
列表和十六進制ID字典之間產生交集:
for entry in images.values():
for key in hexidmap.keys() & entry['hex']:
print('{} {} {}'.format(entry['filename'], key, hexidmap[key]))
&
產生鍵集和十六進制值列表之間的交集。
以上假設您使用的是Python 3; 如果您使用的是Python 2,請使用dict.viewkeys()
而不是.keys()
。
演示:
>>> images = {
... 0: {'hex': ['#c3d6db', '#c7ccc0', '#9a8f6a', '#8a8e3e'], 'filename': 'imag0'},
... 1: {'hex': ['#705b3c', '#6a5639', '#442f1e', '#4a3d28'], 'filename': 'img-xyz'},
... }
>>> hexidmap = {'#b0a7aa': '9976', '#595f5b': '19367', '#9a8f6a': '24095'}
>>> for entry in images.values():
... for key in hexidmap.keys() & entry['hex']:
... print('{} {} {}'.format(entry['filename'], key, hexidmap[key]))
...
imag0 #9a8f6a 24095
for index in d1:
print [(d1[index]["filename"], d2[i], i) for i in d1[index]["hex"] if i in d2]
>>> [('imag0', '24095', '#9a8f6a')]
[]
dicta = {
0: {'hex': ['#c3d6db', '#c7ccc0', '#9a8f6a', '#8a8e3e'], 'filename': 'imag0'},
1: {'hex': ['#705b3c', '#6a5639', '#442f1e', '#4a3d28'], 'filename': 'img-xyz'},
}
dictb = {'#c3d6db': '9976', '#595f5b': '19367', '#9a8f6a': '24095'}
intersection = {}
for o in dicta.values():
intersect = list(set(o['hex']) & set(dictb.keys()))
intersection[o['filename']] = intersect if intersect else "No intersection"
print (intersection)
>>>{'imag0': ['#c3d6db', '#9a8f6a'], 'img-xyz': 'No intersection'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.