【问题标题】:How to find specific key value? [duplicate]如何找到特定的键值? [复制]
【发布时间】:2021-04-19 06:09:25
【问题描述】:
{
 'Key1':{ 'price': 40,
        'amount': 30
       },
 'Key2':{ 'price': 50,
        'amount': 40
       },
 'Key3':{ 'price': 70,
        'amount': 50
       }
}

如何获得所有价格?

【问题讨论】:

    标签: python


    【解决方案1】:

    这是一种方法:

    d={
     'Key1':{ 'price': 40,
            'amount': 30
           },
     'Key2':{ 'price': 50,
            'amount': 40
           },
     'Key3':{ 'price': 70,
            'amount': 50
           }
    }
    
    prices=[k['price'] for i,k in d.items()]
    
    print(prices)
    

    输出:

    [40, 50, 70]
    

    【讨论】:

    • 你也可以在这里使用values()
    • 还有更有意义的名字。 k 通常用于键,但这里的值是 dicts。 vd 会更合适
    【解决方案2】:

    如果字典名为dict1,则使用:

    [k['price'] for k in dict1.values()]
    

    【讨论】:

    • [k['price'] for k in dict1.values()]
    • 道歉。来晚了,我犯了一个错误。
    猜你喜欢
    • 2015-01-06
    • 2012-12-30
    • 2020-10-09
    • 2015-08-29
    • 2012-12-12
    • 2017-05-22
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多