Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over case insensitive sorted dictionary items?

Tags:

python

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.

like image 936
theta Avatar asked Nov 02 '11 08:11

theta


2 Answers

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]
like image 114
Johannes Charra Avatar answered Sep 20 '22 23:09

Johannes Charra


import string
sorted(d.items(), key=string.lower)
like image 25
Katriel Avatar answered Sep 21 '22 23:09

Katriel