How do you iterate over a range of keys in a dictionary?
for example, if I have the following dictionary:
{'Domain Source': 'Analyst', 'Recommend Suppress': 'N', 'Standard Error': '0.25', 'Element ID': '1.A.1.d.1', 'N': '8', 'Scale ID': 'IM', 'Not Relevant': 'n/a', 'Element Name': 'Memorization', 'Lower CI Bound': '2.26', 'Date': '06/2006', 'Data Value': '2.75', 'Upper CI Bound': '3.24', 'O*NET-SOC Code': '11-1011.00'}
how would I iterate over only the keys after standard error? Ideally, I would like to get all the values following standard error.
Thanks!
Just to address the comment: I know about iteritems(), but when I tried subscripting, returned an error: not subscriptable. Also, the key / values come in the same order every time.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
The keys in a Python dictionary are not in any specific order.
You'll want to use an OrderedDict instead.
For example:
>>> d = OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
Now the keys are guaranteed to be returned in order:
>>> d.keys()
['key1', 'key2', 'key3']
If you want to grab all keys after a specific value, you can use itertools.dropwhile:
>>> import itertools
>>> list(itertools.dropwhile(lambda k: k != 'key2', d.iterkeys()))
['key2', 'key3']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With