Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a range of keys in a dictionary?

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.

like image 341
goldisfine Avatar asked Aug 01 '13 21:08

goldisfine


People also ask

Can you iterate over dictionary keys?

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.

How do you iterate in a dictionary?

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.

How do you iterate through a dictionary in a list Python?

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.


1 Answers

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']
like image 97
jterrace Avatar answered Oct 29 '22 20:10

jterrace