Dictionary, separate values and keys into two lists

Asked

Viewed 728 times

2

I have the following dictionary:

abc = {'y': 'Y', 'b': 'B', 'e': 'E', 'x': 'X', 'v': 'V', 't': 'T', 'f': 'F', 'w': 'W', 'g': 'G', 'o': 'O', 'j': 'J', 'm': 'M', 'z': 'Z', 'h': 'H', 'd': 'D', 'r': 'R', 'l': 'L', 'p': 'P', 'a': 'A', 's': 'S', 'k': 'K', 'n': 'N', 'q': 'Q', 'i': 'I', 'u': 'U', 'c': 'C'}

What I wanted is to separate the values and the keys into two different lists. And sort each one, the result I want:

lista_peq = ['a', 'b', 'c' ...]
lista_grd = ['A', 'B', 'C' ...]

1 answer

4


This solution I will give you works on both python 2.7.x and python 3.x. x.

To separate

abc = {'y': 'Y', 'b': 'B', 'e': 'E', 'x': 'X', 'v': 'V', 't': 'T', 'f': 'F', 'w': 'W', 'g': 'G', 'o': 'O', 'j': 'J', 'm': 'M', 'z': 'Z', 'h': 'H', 'd': 'D', 'r': 'R', 'l': 'L', 'p': 'P', 'a': 'A', 's': 'S', 'k': 'K', 'n': 'N', 'q': 'Q', 'i': 'I', 'u': 'U', 'c': 'C'}

in two lists, one with lowercase letters and the other with uppercase letters and order them do so:

lista_peq = sorted(abc.keys()) #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
lista_grd = sorted(abc.values()) #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

abc.values() will extract the values and abc.keys() will extract keys. The method sorted(...) in the case of python 2.7.x will sort alphabetically, and in the case of python 3.x in addition to sort will also convert into list implicitly. To convert only list (without being ordered) in python 3.x would be list(abc.keys()) and list(abc.values()).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.