简体   繁体   中英

Sorted working differently with '&' in one of the list elements

if we have a dict and convert it

a={'pop': 1, 'Christmas': 1, 'R&B': 2}

and then we use sorted

sorted(list(a))

why does it return this?:

['Christmas', 'R&B', 'pop']
>>> a={'pop': 1, 'Christmas': 1, 'R&B': 2}
>>> list(a)
['pop', 'Christmas', 'R&B']

list(a) is the keys in the dictionary and sorted() sorts the keys.

list(a) gives list of dictionary keys and sorted sorts it. Because your keys are a mix of uppercase and lowercase characters, you won't expect it to return in required way as uppercase letters are sorted before lowercase.

One way to handle this is to define a custom function like:

a = {'pop': 1, 'Christmas': 1, 'R&B': 2}

def lower(x):
    return x.lower()

print(sorted(list(a), key=lower))
# ['Christmas', 'pop', 'R&B']

If you are trying to sort by length of words, this would be the way:

a = {'pop': 1, 'Christmas': 1, 'R&B': 2}

print(sorted(list(a), key=len))
# ['pop', 'R&B', 'Christmas']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM