Looping over a dictionary without first and last element

11,909

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

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 3

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 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'}
Share:
11,909
Tim C.
Author by

Tim C.

Updated on June 28, 2022

Comments

  • Tim C.
    Tim C. almost 2 years

    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)

  • Zack Tarr
    Zack Tarr over 6 years
    Written for 2.7 but I will look at updating the code for both.
  • chepner
    chepner over 6 years
    In 3.6, it is still an implementation-specific optimization that dictionaries keep keys in insertion order.
  • srikavineehari
    srikavineehari over 6 years
    @chepner, agree.
  • Sohaib Farooqi
    Sohaib Farooqi over 6 years
    This should be the accepted answer, as it deals with unordered nature of dict and a nice explanation as well
  • Sohaib Farooqi
    Sohaib Farooqi over 6 years
    Modify you answer so that it grab all keys like list(capitals.keys()) . It will be compatible with both 2.7 and 3.x
  • RoadRunner
    RoadRunner over 6 years
    @GarbageCollector Cheers, I thought it would be a bit easier for the OP to understand if I cover the issues step by step.
  • Zack Tarr
    Zack Tarr over 6 years
    Does capitals.keys() not return a list in 3.x? It looks like the pop function is supported in 3.x as well. I havent had a chance to install python 3 so havent tested.
  • RoadRunner
    RoadRunner over 6 years
    @StefanPochmann Funny thing is, another answer also said the same thing, but you didn't comment on that. Python 3.6 doesn't have guaranteed ordered dictionaries currently, its still in the process. Either way, I removed that comment.
  • Stefan Pochmann
    Stefan Pochmann over 6 years
    Well I didn't feel like asking two people about it, and yours was the higher-voted one (with one vote from me for the round-trip idea :-)
  • Wondercricket
    Wondercricket over 6 years
    @ZackTarr keys in Python 3.x does not return a list - it returns a view object containing the keys of the dictionary
  • RoadRunner
    RoadRunner over 6 years
    Cheers mate, I was just curious is all. I hope I didn't sound rude. I should use "dictionaries are inherently unordered" with caution, since its not technically true anymore. Looking forward to the guaranteed ordered dicts in Python 3.7.
  • Fuji
    Fuji over 2 years
    This unnecessary puts the data in memory and requires two iterations