Looping over a dictionary without first and last element
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'}
Tim C.
Updated on June 28, 2022Comments
-
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 over 6 yearsWritten for 2.7 but I will look at updating the code for both.
-
chepner over 6 yearsIn 3.6, it is still an implementation-specific optimization that dictionaries keep keys in insertion order.
-
srikavineehari over 6 years@chepner, agree.
-
Sohaib Farooqi over 6 yearsThis should be the accepted answer, as it deals with unordered nature of
dict
and a nice explanation as well -
Sohaib Farooqi over 6 yearsModify you answer so that it grab all keys like
list(capitals.keys())
. It will be compatible with both 2.7 and 3.x -
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 over 6 yearsDoes 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 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 over 6 yearsWell 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 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 over 6 yearsCheers 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 over 2 yearsThis unnecessary puts the data in memory and requires two iterations