You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问有序字典的键值?如何获取指定OrderedDict中cost_price的0.92值

Hey there! Let's tackle your two questions about accessing values in an OrderedDict clearly and simply:

1. How to access keys and values in an Ordered Dictionary

Since OrderedDict is a subclass of Python's regular dictionary, most of the access methods you use for standard dicts work here too—with the added bonus that the insertion order of keys is preserved. Here are the common ways:

  • Direct access by key: Just like a normal dict, use square brackets to get a value by its key. For example:
    from collections import OrderedDict
    od = OrderedDict([('a', 1), ('b', 2)])
    value_a = od['a']  # Returns 1
    
    If you want to avoid KeyError when the key doesn't exist, use the get() method with an optional default value:
    value_c = od.get('c', 0)  # Returns 0 since 'c' isn't a key
    
  • Iterate over key-value pairs: Loop through items() to get each key and its corresponding value in order:
    for key, value in od.items():
        print(f"Key: {key}, Value: {value}")
    
  • Get lists of keys or values: Convert the keys/values views to lists to access them by index (though remember, relying on index is less common than using keys):
    keys_list = list(od.keys())  # ['a', 'b']
    values_list = list(od.values())  # [1, 2]
    
2. How to get the '0.92' value corresponding to 'cost_price' in your specific OrderedDict

First, let's restate your sample OrderedDict for clarity:

from collections import OrderedDict

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

This is a nested structure: the outer OrderedDict has a key '0' that maps to another inner OrderedDict. To get the '0.92' value, you need to first access the inner dict, then grab the 'cost_price' key.

Method 1: Direct chained access

This is the simplest way if you're sure the keys exist:

cost_price = target_dict['0']['cost_price']
# Result is the string '0.92'—if you need a float, convert it with float(cost_price)

Method 2: Safe access with get()

If you want to handle cases where '0' or 'cost_price' might be missing (to avoid KeyError), use get() at each level:

inner_dict = target_dict.get('0', {})  # Return empty dict if '0' doesn't exist
cost_price = inner_dict.get('cost_price', None)  # Return None if 'cost_price' is missing

Either way, you'll end up with the '0.92' value you're looking for!

内容的提问来源于stack exchange,提问作者Sanjay Dgsk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:17