如何访问有序字典的键值?如何获取指定OrderedDict中cost_price的0.92值
Hey there! Let's tackle your two questions about accessing values in an OrderedDict clearly and simply:
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:
If you want to avoidfrom collections import OrderedDict od = OrderedDict([('a', 1), ('b', 2)]) value_a = od['a'] # Returns 1KeyErrorwhen the key doesn't exist, use theget()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]
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

