Skip to content Skip to sidebar Skip to footer

Looping Over A Dictionary Without First And Last Element

I would like to know how I can loop over a Python dictionary without first and last element. My keys doesn't start at 1 so I can't use len(capitals) >>> capitals = {'15':'

Solution 1:

Try this, by converting dictionary to list, then print list

c=[city for key,city in capitals.items()]
c[1:-1]

Output

['New York', 'Berlin', 'Brasilia']

Solution 2:

Since dicts are inherently unordered, you would have to order its items first. Given your example data, you want to skip the first and last by key:

for k in sorted(capitals)[1:-1]:
    print(capitals[k])

Solution 3:

Dictionaries are ordered in Python 3.6+

You could get the cities except the first and the last with list(capitals.values())[1:-1].

capitals = {'15':'Paris', '16':'New York', '17':'Berlin', '18':'Brasilia', '19':'Moscou'}

for city in list(capitals.values())[1:-1]:
    print(city)

New York
Berlin
Brasilia
>>> 

On Fri, Dec 15, 2017, Guido van Rossum announced on the mailing list: "Dict keeps insertion order" is the ruling.

Solution 4:

You could put the data first into a list of tuples with list(capitals.items()), which is an ordered collection:

[('15','Paris'), ('16','New York'), ('17', 'Berlin'), ('18', 'Brasilia'), ('19', 'Moscou')]

Then convert it back to a dictionary with the first and last items removed:

capitals = dict(capitals[1:-1])

Which gives a new dictionary:

{'16': 'New York', '17': 'Berlin', '18': 'Brasilia'}

Then you can loop over these keys in your updated dictionary:

for city in capitals:
    print(capitals[city])

and get the cities you want:

New York
Berlin
Brasilia

Solution 5:

I have to disagree with previous answer and also with Guido's comment saying that "Dict keep insertion order". Dict doesn't keep insertion order all the time. I just tried (on a pyspark interpretor though, but still) and the order is changed. So please look carefully at your environement and do a quick test before running such a code. To me, there is just no way to do that with 100% confidence in Python, unless you explicitly know the key to remove, and if so you can use a dict comprehension:

myDict = {key:val for key, val in myDict.items() if key != '15'}

Post a Comment for "Looping Over A Dictionary Without First And Last Element"