简体   繁体   中英

Python - How to sort both key and value alphabetically

I have a dictionary like this:

d = {
   'yellow': ['C','A','F'], 
   'blue': ['D','A'],
   'brown': ['G','Z'],
   'red': ['F','T'],
   'green': ['Z','A']
}

I'm trying to get output like this:

{
    'blue': ['A','D'],
    'brown': ['G','Z'],
    'green': ['A','Z']}
    'red': ['F','T'],
    'yellow': ['A','C','F']
} 

I'm trying to sort key and value alphabetically. I've tried using modules to do this, but how to do it without using modules?

>>> d = {'yellow': ['C','A','F'],
...  'blue': ['D','A'],
...  'brown': ['G','Z'],
...  'red': ['F','T'],
...  'green': ['Z','A']}
>>>
>>> {key: sorted(val) for key, val in sorted(d.items())}
{'blue': ['A', 'D'], 'brown': ['G', 'Z'], 'green': ['A', 'Z'], 'red': ['F', 'T'], 'yellow': ['A', 'C', 'F']}

You'll need Python 3.7+ for dicts to remember their key insertion order. Then you can use:

dict(sorted((k, sorted(v)) for k, v in d.items()))

edit: I also like this one.

{k: sorted(d[k]) for k in sorted(d)}

try this code:

data = {'yellow': ['C', 'A', 'F'],
    'blue': ['D', 'A'],
    'brown': ['G', 'Z'],
    'red': ['F', 'T'],
    'green': ['Z', 'A']}

res = {} # New Sorted Dict
sorted_keys = sorted(data.keys()) # sorted keys

for key in sorted_keys:
    res[key] = sorted(data.get(key)) # Sorted values For key
print(res)

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