簡體   English   中英

用另一個字典的值替換一個字典的鍵

[英]Replace keys of one dictionary by the values of other

我有 2 個字典,想用它們的鍵加入它們,output 字典應該只有兩個字典的值

counter = Counter({0: 1702,
                 1: 1920,
                 2: 1851,
                 3: 1882,
                 4: 1745,
                 5: 1741,
                 6: 1827,
                 7: 1961,
                 8: 1790,
                 9: 1926})
labels = 
        {0: 'Tomato___Bacterial_spot',
         1: 'Tomato___Early_blight',
         2: 'Tomato___Late_blight',
         3: 'Tomato___Leaf_Mold',
         4: 'Tomato___Septoria_leaf_spot',
         5: 'Tomato___Spider_mites Two-spotted_spider_mite',
         6: 'Tomato___Target_Spot',
         7: 'Tomato___Tomato_Yellow_Leaf_Curl_Virus',
         8: 'Tomato___Tomato_mosaic_virus',
         9: 'Tomato___healthy'}

Output

 "Tomato___Bacterial_spot": 1920,
        "Tomato___healthy": 1926,
from collections import Counter

counter = Counter({0: 1702,
                   1: 1920,
                   2: 1851,
                   3: 1882,
                   4: 1745,
                   5: 1741,
                   6: 1827,
                   7: 1961,
                   8: 1790,
                   9: 1926})

labels = {0: 'Tomato___Bacterial_spot',
          1: 'Tomato___Early_blight',
          2: 'Tomato___Late_blight',
          3: 'Tomato___Leaf_Mold',
          4: 'Tomato___Septoria_leaf_spot',
          5: 'Tomato___Spider_mites Two-spotted_spider_mite',
          6: 'Tomato___Target_Spot',
          7: 'Tomato___Tomato_Yellow_Leaf_Curl_Virus',
          8: 'Tomato___Tomato_mosaic_virus',
          9: 'Tomato___healthy'}

res = {}
for k, v in labels.items():
    res[v] = counter[k]

print(res)

或者類似地,您可以使用字典理解:

res2 = {v: counter[k] for k, v in labels.items()}
print(res2)

暫無
暫無

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

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