简体   繁体   English

如何对字典 python 的每个键的值进行排序?

[英]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:您可以使用嵌套的 dict 理解:

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.正如我在评论中提到的,如果您只需要将csv作为dict阅读, pandas就有点过头了。 Look into thecsv.DictReader object as a viable alternative.查看csv.DictReader object作为可行的替代方案。

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: 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如果您还需要对键进行排序,您将需要和有序的 dict

You can use dict comprehension for a one line solution, although it will become harder to read.您可以将 dict 理解用于单行解决方案,尽管它会变得更难阅读。 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: 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该解决方案假设您在外部字典中只有一个元素,键为 0。如果您有更多元素并应用相同的逻辑,则可以遍历字典键
  • 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如果您的数字超过 1 位,则必须在排序之前将元素转换为 int,否则它们将按字母顺序排序

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'}}结果: {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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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