简体   繁体   中英

How to sort the values of each key of dictionary python?

I have such a dictionary:

df = pd.read_csv(file, header=None)
l = (df.to_dict())
{0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}

and I want to sort the values of each key in descending order which will be:

 {0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

You can use a nested dict comprehension:

sep = ' '
result = {
  row: {
    k: sep.join(sorted(v.split(sep), reverse=True))
    for k, v in val.items() 
  } for row, val in l.items()
}

Result:

{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

As mentioned in my comment, if you only need to read a csv as a dict , pandas is rather overkill. Look into thecsv.DictReader object as a viable alternative.

You can use one temporary dictionnary and two loops

for key, value in d.items():
    tmp = {}
    for key1, value1 in value.items():
        tmp[key1] = ' '.join(sorted(value1.split(' '), reverse=True))
    d[key] = tmp

output:

{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

You can use dict comprehension to create a new dict, with the values sorted.

df = pd.read_csv(file, header=None)
l = (df.to_dict())

{key:sorted(value) for key, value in l['0'].items()}

Since your data is not properly formated, you can turn space delimited strings of numbers into list using "split".

df = pd.read_csv(file, header=None)
l = (df.to_dict())

{key:sorted(value.split(' ')) for key, value in l['0'].items()}

If you need to sort the keys as well, you will need and ordered dict

You can use dict comprehension for a one line solution, although it will become harder to read. You'll have to split the string into a list, sort it, and then join it back. You can try something like this:

dict = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}
result = { 0 : { key : ' '.join(sorted(dict[0][key].split(),reverse=True)) for key in dict[0].keys() } }

Output:

>>> result
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

Note:

  • The solution assumes you only have one element in the outer dictionary, with the key 0. You can loop through the dictionary keys if you have more elements and apply the same logic
  • The solution assumes all the element are only digits. If you have numbers of more than 1 digit you'll have to cast the elements to int before sorting, otherwise they will be sorted alphabetically

Here's a solution using several list/dictionary comprehensions:

d = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}} # original dictionary

# grab the inner dictionary to sort
inner_d = list(d.values())[0]

# reverse order as int
sorted_vals = [sorted(list(map(int, i.split())))[::-1] for i in inner_d.values()]

# convert back to list of joined strings
sorted_vals = [" ".join(a) for a in [[str(j) for j in i] for i in sorted_vals]] 

# rebuild inner dictionary
inner_d = {k:v for k,v in zip(inner_d.keys(), sorted_vals)}

# put back into outer dictionary
d = {0:inner_d}

Result: {0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

Here's a way:

a = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}

for k in a[0].keys():
    a[0].update({k:' '.join(sorted(a[0][k].split(),reverse=True))})

print(a)

Output:

{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}

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