theta
theta

Reputation: 25631

How to iterate over case insensitive sorted dictionary items?

Example:

>>> d = {'answer':1, 'Question':2}
>>> for i, j in sorted(d.items()): print i
Question
answer

I would like case insensitive list:

answer
Question

and I believe it can be done in simple Pythonic way.

Upvotes: 7

Views: 4328

Answers (3)

Cito
Cito

Reputation: 5613

for k in sorted(d, key=lambda k: k.lower()):
    print k

Upvotes: 2

Johannes Charra
Johannes Charra

Reputation: 29953

If it's just about printing the keys:

for i in sorted(d.keys(), key=lambda x: x.lower()): print i

If you need the values afterwards, you could do

for i, j in sorted(d.items(), key=lambda x: x[0].lower()): print i, j

EDIT: Even shorter and better (since you have d in scope):

for i in sorted(d, key=str.lower):
    print i, d[i]

Upvotes: 10

Katriel
Katriel

Reputation: 123762

import string
sorted(d.items(), key=string.lower)

Upvotes: 3

Related Questions