【问题标题】:How to access key values in ordered dictionary如何访问有序字典中的键值
【发布时间】:2018-09-12 15:22:29
【问题描述】:

如何访问此有序字典中的值..我想访问 cost_price 中的值,即 0.92。

OrderedDict([('0', OrderedDict([('cost_price', '0.92'), ('quantity', '0'), ('sell_price', '1.69'), ('text', '6oz')]))])

【问题讨论】:

  • 和平常一样Dictionary.
  • 你试过什么?什么不起作用?

标签: python django python-3.x dictionary ordereddictionary


【解决方案1】:

如果您事先知道您的 cost_price 只有一个条目,我会将next 与生成器表达式一起使用。

如上所述,这与普通字典没有什么不同。

from collections import OrderedDict

d = OrderedDict([('0', OrderedDict([('cost_price', '0.92'), ('quantity', '0'), ('sell_price', '1.69'), ('text', '6oz')]))])

res = next((d[i] for i in d if d[i]['cost_price'] == '0.92'), None)

结果:

OrderedDict([('cost_price', '0.92'),
             ('quantity', '0'),
             ('sell_price', '1.69'),
             ('text', '6oz')])

按键获取所有 cost_price 值:

res = {k: d[k]['cost_price'] for k in d}

# {'0': '0.92'}

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2022-11-03
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多