首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将一个字典的键替换为另一个字典的值

将一个字典的键替换为另一个字典的值
EN

Stack Overflow用户
提问于 2021-05-23 15:30:51
回答 1查看 20关注 0票数 0

我有2个字典,并希望连接他们的关键字,输出字典应该只有两个字典的值

代码语言:javascript
复制
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'}

输出

代码语言:javascript
复制
 "Tomato___Bacterial_spot": 1920,
        "Tomato___healthy": 1926,
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-23 15:38:06

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
res2 = {v: counter[k] for k, v in labels.items()}
print(res2)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67657270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档