无法在python dict中搜索密钥

时间:2017-05-08 16:05:44

标签: python python-2.7

我有下面的词典 -

import collections
tags = [
    {
        "Key": "Name",
        "Value": "Peter"
    },
    {
        "Key": "Email",
        "Value": "Peter@xyz.com"

    },
    {
        "Key": "City",
        "Value": "Paris"

    },
]

我试图留意Email地址的价值,但我无法做到。

请建议我找到这个值的逻辑 -

2 个答案:

答案 0 :(得分:4)

tags进行迭代,检查每个tag的{​​{1}} 'Key'。找到后,获取'Email'

'Value'

答案 1 :(得分:3)

试试这个:

[dic['Value'] for dic in tags if dic['Key'] =="Email"]

输出:

['Peter@xyz.com']

更新多个值:

假设你有:

tags = [
    {
        "Key": "Name",
        "Value": "Peter"
    },
    {
        "Key": "Email",
        "Value": "Peter@xyz.com"

    },
    {
        "Key": "Email",
        "Value": "test@xyz.com"

    },

    {
        "Key": "City",
        "Value": "Paris"

    },
]

输出将是:

['Peter@xyz.com', 'test@xyz.com']