Tim C.
Tim C.

Reputation: 187

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':'Paris', '16':'New York', '17':'Berlin', '18':'Brasilia', '19':'Moscou'}
>>> for city in capitals:
>>>     print(city)
Paris
New York
Berlin
Brasilia
Moscou

I would like this result:

New York
Berlin
Brasilia

My keys doesn't start at 1 so I can't use len(capitals)

Upvotes: 5

Views: 22582

Answers (7)

N.dP
N.dP

Reputation: 51

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'}

Upvotes: 3

user9158931
user9158931

Reputation:

You can sort dict and then just fetch all values except first and last :

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

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

output:

New York
Berlin
Brasilia

In one line:

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

Upvotes: 1

Zack Tarr
Zack Tarr

Reputation: 851

As mentioned in the comments. A dictionary is not setup to store data in order, a list would be better for that. Such as a 2d list like [[15,'Paris'],[ [16,'New York'],....]

Below is the code that will get all of the keys (numbers) from the dictionary and put them in the list keys. Then I pop the first (0) element of the list and then use for loop to pull each city with the keys left in the list.

capitals={'15':'Paris', '16':'New York', '17':'Berlin', '18':'Brasilia', '19':'Moscou'}
keys=list(capitals.keys()) #get list of keys from dictionary
keys.pop(0)  #Remove first in list of keys
for key in keys:
    print capitals[key]

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26315

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

Upvotes: 3

Artier
Artier

Reputation: 1673

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']

Upvotes: 5

neehari
neehari

Reputation: 2612

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.

Upvotes: 3

user2390182
user2390182

Reputation: 73460

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])

Upvotes: 3

Related Questions