如何按键对字典排序?

{2:3, 1:89, 4:5, 3:0}{1:89, 2:3, 3:0, 4:5}什么?
我检查了一些帖子,但它们都使用了返回元组的“排序”运算符。


#1楼

字典本身没有这样的有序项目,如果您想按某种顺序打印它们,下面是一些示例:

Python 2.4及更高版本中:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict):
    print "%s: %s" % (key, mydict[key])

给出:

alan: 2
bob: 1
carl: 40
danny: 3

(低于2.4的Python :)

keylist = mydict.keys()
keylist.sort()
for key in keylist:
    print "%s: %s" % (key, mydict[key])

资料来源: http : //www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/


#2楼

Python的collections库文档中

>>> from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

#3楼

在Python 3中。

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

1 89
2 3
3 0
4 5

#4楼

在这里,我找到了一些最简单的解决方案,可以使用pprint按键对python字典进行排序。 例如。

>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99} 
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}

但是在使用pprint时,它将返回排序的字典

>>> import pprint 
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

#5楼

找到了另一种方法:

import json
print json.dumps(d, sort_keys = True)

更新:
1.这也对嵌套对象进行排序(感谢@DanielF)。
2. python字典是无序的,因此可用于打印或仅分配给str。


#6楼

Python字典是无序的。 通常,这不是问题,因为最常见的用例是进行查找。

执行所需操作的最简单方法是创建一个collections.OrderedDict ,按排序顺序插入元素。

ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])

如上面其他建议那样,如果需要迭代,最简单的方法是迭代排序的键。 例子-

打印按键排序的值:

# create the dict
d = {k1:v1, k2:v2,...}
# iterate by keys in sorted order
for k in sorted(d.keys()):
    value = d[k]
    # do something with k, value like print
    print k, value

获取按键排序的值列表:

values = [d[k] for k in sorted(d.keys())]

#7楼

有许多Python模块提供字典实现,这些实现将按顺序自动维护键。 考虑sortedcontainers模块,它是纯Python和快速C实现。 还与其他基准测试的流行选项进行性能比较

如果您需要在迭代过程中不断添加和删除键/值对,则使用有序dict是不适当的解决方案。

>>> from sortedcontainers import SortedDict
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> s = SortedDict(d)
>>> s.items()
[(1, 89), (2, 3), (3, 0), (4, 5)]

SortedDict类型还支持索引位置查找和删除,这是内置dict类型无法实现的。

>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])

#8楼

只是:

d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())

for k,v in sd:
    print k, v

输出:

1 89
2 3
3 0
4 5

#9楼

伙计们,你让事情变得复杂了……这很简单

from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)

输出为:

{'A':2,'B':1,'C':3}

#10楼

2.7中这两种方法的时序比较显示它们实际上是相同的:

>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181

>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745 

#11楼

l = dict.keys()
l2 = l
l2.append(0)
l3 = []
for repeater in range(0, len(l)):
    smallnum = float("inf")
    for listitem in l2:
        if listitem < smallnum:
            smallnum = listitem
    l2.remove(smallnum)
    l3.append(smallnum)
l3.remove(0)
l = l3

for listitem in l:
    print(listitem)

#12楼

from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
    {'fname': 'Mo', 'lname': 'Mahjoub'},
    {'fname': 'Abdo', 'lname': 'Al-hebashi'},
    {'fname': 'Ali', 'lname': 'Muhammad'}
]
#  This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first. 
for k in sorted (user, key=itemgetter ('fname', 'lname')):
    print (k)

# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
    print (x)

#13楼

有一种简单的方法可以对字典进行排序。

根据您的问题,

解决方案是:

c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y

(其中c是您的字典的名称。)

该程序提供以下输出:

[(1, 89), (2, 3), (3, 0), (4, 5)]

就像你想要的。

另一个示例是:

d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x

给出输出: ['Albert', 'Bill', 'John', 'Lucy', 'Peter']

y=sorted(d.values())
print y

给出输出: [18, 24, 32, 36, 41]

z=sorted(d.items())
print z

给出输出:

[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]

因此,通过将其更改为键,值和项,您可以按需要打印,希望这会有所帮助!


#14楼

最简单的解决方案是,您应该获得一个dict键的列表,该键是排序顺序,然后遍历dict。 例如

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print r, a1[r]

以下是输出(降序)

e 30
b 13
d 4
c 2
a 1

#15楼

将会生成您想要的东西:

 D1 = {2:3, 1:89, 4:5, 3:0}

 sort_dic = {}

 for i in sorted(D1):
     sort_dic.update({i:D1[i]})
 print sort_dic


{1: 89, 2: 3, 3: 0, 4: 5}

但这不是执行此操作的正确方法,因为它可能会显示不同词典的不同行为,这是我最近学到的。 因此,Tim在我在这里分享的Query的响应中提出了一种完美的方法。

from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

#16楼

我认为最简单的方法是按键对字典进行排序,然后将排序后的key:value对保存到新字典中。

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

为了更清楚一点:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value

#17楼

dictionary = {1:[2],2:[],5:[4,5],4:[5],3:[1]}

temp=sorted(dictionary)
sorted_dict = dict([(k,dictionary[k]) for i,k in enumerate(temp)])

sorted_dict:
         {1: [2], 2: [], 3: [1], 4: [5], 5: [4, 5]}

#18楼

对于CPython / PyPy 3.6和任何Python 3.7或更高版本,可以使用以下方法轻松完成此操作:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}

#19楼

Python字典在Python 3.6之前是无序的。 在Python 3.6的CPython实现中,字典保留插入顺序。 从Python 3.7开始,这将成为一种语言功能。

在Python 3.6的更新日志中( https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict ):

此新实现的顺序保留方面被认为是实现细节,因此不应依赖(将来可能会更改,但是希望在更改语言规范之前,先在几个发行版中使用该新dict实现该语言,为所有当前和将来的Python实现强制要求保留顺序的语义;这还有助于保留与仍旧有效的随机迭代顺序的旧版本语言(例如Python 3.5)的向后兼容性。

在Python 3.7的文档中( https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries ):

在字典上执行list(d)会以插入顺序返回字典中使用的所有键的列表(如果要对其进行排序,请改用sorted(d))。

因此,与以前的版本不同,您可以在Python 3.6 / 3.7之后对字典进行排序。 如果要对嵌套的字典(包括其中的子字典)进行排序,则可以执行以下操作:

test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}

def dict_reorder(item):
    return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}

reordered_dict = dict_reorder(test_dict)

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb


#20楼

您可以根据问题按关键字对当前词典进行排序,从而创建新词典。

这是你的字典

d = {2:3, 1:89, 4:5, 3:0}

通过使用lambda函数对d排序来创建新字典d1

d1 = dict(sorted(d.items(), key = lambda x:x[0]))

d1应该为{1:89,2:3,3:0,4:5},根据d中的键排序。


#21楼

或使用pandas

演示:

>>> d={'B':1,'A':2,'C':3}
>>> df=pd.DataFrame(d,index=[0]).sort_index(axis=1)
   A  B  C
0  2  1  3
>>> df.to_dict('int')[0]
{'A': 2, 'B': 1, 'C': 3}
>>> 

看到:

这个文档

大熊猫的文献资料


#22楼

我提出单行字典排序。

>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]

希望这会有所帮助。


#23楼

另一种pythonic方法是

def sort_dict(my_dict):
    return sorted(my_dict.items(), key=lambda x :x[1])



#24楼

此函数将按其键对任何字典进行递归排序。 也就是说,如果字典中的任何值也是字典,那么它也将通过其键进行排序。 如果您在CPython 3.6或更高版本上运行,则可以简单地更改为使用dict而不是OrderedDict

from collections import OrderedDict

def sort_dict(d):
    items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])]
    for item in items:
        if isinstance(item[1], dict):
            item[1] = sort_dict(item[1])
    return OrderedDict(items)
    #return dict(items)

#25楼

标准Python字典是无序的。 即使您对(键,值)对进行了排序,也无法以保留顺序的方式将它们存储在dict中。

最简单的方法是使用OrderedDict ,它可以记住元素插入的顺序:

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

没关系od的打印方式; 它会按预期工作:

In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....: 
1 89
2 3
3 0
4 5

Python 3

对于Python 3用户,需要使用.items()而不是.iteritems()

In [13]: for k, v in od.items(): print(k, v)
   ....: 
1 89
2 3
3 0
4 5

#26楼

正如其他人所提到的,字典本质上是无序的。 但是,如果问题仅是按顺序显示字典,则可以覆盖字典子类中的__str__方法,并使用此字典类而不是内置dict 。 例如。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}

请注意,这不会改变密钥的存储方式,迭代时它们返回的顺序等,也不会改变它们在print或python控制台上的显示方式。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值