Ant*_*ony 838 python sorting dictionary
这将是一个很好的方式,从去{2:3, 1:89, 4:5, 3:0}
到{1:89, 2:3, 3:0, 4:5}
?
我检查了一些帖子,但他们都使用返回元组的"已排序"运算符.
NPE*_*NPE 874
标准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)])
Run Code Online (Sandbox Code Playgroud)
别介意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
Run Code Online (Sandbox Code Playgroud)
对于Python 3用户,需要使用.items()
而不是.iteritems()
:
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 395
字典本身没有这样的订购商品,如果你想将它们打印成某种订单,这里有一些例子:
在Python 2.4及以上版本中:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
Run Code Online (Sandbox Code Playgroud)
得到:
alan: 2
bob: 1
carl: 40
danny: 3
Run Code Online (Sandbox Code Playgroud)
(Python低于2.4 :)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
Run Code Online (Sandbox Code Playgroud)
资料来源:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
Den*_*nis 195
>>> 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)])
Run Code Online (Sandbox Code Playgroud)
Dip*_*ipu 100
对于python3.6 +,可以通过以下方式轻松完成:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
Run Code Online (Sandbox Code Playgroud)
Gra*_*ntJ 41
有许多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)]
Run Code Online (Sandbox Code Playgroud)
SortedDict类型还支持索引位置查找和删除,这是内置dict类型无法实现的.
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
Run Code Online (Sandbox Code Playgroud)
小智 27
只是:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
Run Code Online (Sandbox Code Playgroud)
输出:
1 89
2 3
3 0
4 5
Run Code Online (Sandbox Code Playgroud)
Bri*_*ian 24
正如其他人所提到的,词典本质上是无序的.但是,如果问题仅仅是以有序方式显示字典,则可以__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}
Run Code Online (Sandbox Code Playgroud)
注意,这不会改变密钥的存储方式,迭代它们时会返回的顺序等等,它们是如何print
在python控制台上显示的.
the*_*est 24
这里有很多答案已经展示了对 Python 字典进行排序的流行方法。我想我应该为那些从谷歌来到这里寻找非标准想法的人添加一些不太明显的方法。
示例词典:d = {2: 'c', 1: 'b', 0: 'a', 3: 'd'}
# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}
Run Code Online (Sandbox Code Playgroud)
排序并不总是严格按照升序或降序排列。对于更多条件排序,可以将上述方法与 lamda 结合使用:
{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}
Run Code Online (Sandbox Code Playgroud)
该线程已经充满了足够的好例子。有关更多示例以及边缘情况和奇怪之处,请查看这篇有关 Python 中字典排序的文章。
tsc*_*ket 18
找到另一种方式:
import json
print json.dumps(d, sort_keys = True)
Run Code Online (Sandbox Code Playgroud)
upd:
1.这也可以对嵌套对象进行排序(感谢@DanielF).
2. python词典是无序的,因此这对于打印或仅分配给str是可取的.
m3.*_*3.b 18
我发现对字典进行排序的一种简单方法是根据您要排序的字典的已排序键:值项创建一个新字典。如果要排序dict = {}
,请使用关联方法检索其所有项目,使用该sorted()
函数对它们进行排序,然后创建新字典。
这是使用字典理解的代码:
sorted_dict = {k:v for k,v in sorted(dict.items())}
Run Code Online (Sandbox Code Playgroud)
Evg*_*sin 16
在Python 3中.
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
Run Code Online (Sandbox Code Playgroud)
给
1 89
2 3
3 0
4 5
Run Code Online (Sandbox Code Playgroud)
pr9*_*r94 16
一个简单的方法来做到这一点:
d = {2:3, 1:89, 4:5, 3:0}
s = {k : d[k] for k in sorted(d)}
s
Run Code Online (Sandbox Code Playgroud)
Out[1]: {1: 89, 2: 3, 3: 0, 4: 5}
Run Code Online (Sandbox Code Playgroud)
Gua*_* Li 12
Python字典在Python 3.6之前是无序的.在Python 3.6的CPython实现中,字典保持插入顺序.从Python 3.7开始,这将成为一种语言功能.
如果你想对嵌套的dict进行排序,包括里面的sub-dict,你可以这样做:
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)
Run Code Online (Sandbox Code Playgroud)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
Atu*_*ind 11
在这里,我找到了一些最简单的解决方案来使用key对python dict进行排序pprint
.例如.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
Run Code Online (Sandbox Code Playgroud)
但是在使用pprint时它将返回已排序的dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
Run Code Online (Sandbox Code Playgroud)
Meh*_*ssi 11
以下是建议解决方案的性能:
\nfrom collections import OrderedDict\nfrom sortedcontainers import SortedDict\nimport json\n\nkeys = np.random.rand(100000)\nvals = np.random.rand(100000)\n\nd = dict(zip(keys, vals))\n\ntimeit SortedDict(d)\n#45.8 ms \xc2\xb1 780 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\ntimeit sorted(d.items())\n#91.9 ms \xc2\xb1 707 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\ntimeit OrderedDict(sorted(d.items(), key=lambda x: x[0]))\n#93.7 ms \xc2\xb1 1.52 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\ntimeit dict(sorted(dic.items()))\n#113 ms \xc2\xb1 824 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\ntimeit OrderedDict(sorted(dic.items()))\n#122 ms \xc2\xb1 2.65 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\ntimeit json.dumps(d, sort_keys=True)\n#259 ms \xc2\xb1 9.42 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 1 loop each)\n
Run Code Online (Sandbox Code Playgroud)\n正如我们所见,Grant Jenks 的解决方案是迄今为止最快的。
\n小智 9
有一种简单的方法来排序字典.
根据你的问题,
解决方案是:
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
Run Code Online (Sandbox Code Playgroud)
(其中c是你字典的名称.)
该程序提供以下输出:
[(1, 89), (2, 3), (3, 0), (4, 5)]
Run Code Online (Sandbox Code Playgroud)
就像你想要的那样
另一个例子是:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Run Code Online (Sandbox Code Playgroud)
给出输出:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Run Code Online (Sandbox Code Playgroud)
给出输出:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Run Code Online (Sandbox Code Playgroud)
给出输出:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Run Code Online (Sandbox Code Playgroud)
因此,通过将其更改为键,值和项目,您可以打印出您想要的内容.希望这有帮助!
会产生你想要的东西:
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}
Run Code Online (Sandbox Code Playgroud)
但这不是写这种方式,因为它可以显示不同字典的不同行为,我最近学到了这些.因此Tim提出了完美的方式在我的查询的回答中,我在这里分享.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
Run Code Online (Sandbox Code Playgroud)
我认为最简单的方法是按键对字典进行排序,然后将排序后的键:值对保存在新字典中。
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]
Run Code Online (Sandbox Code Playgroud)
为了更清楚一点:
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
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以根据问题按关键字对当前词典进行排序,从而创建新词典。
这是你的字典
d = {2:3, 1:89, 4:5, 3:0}
Run Code Online (Sandbox Code Playgroud)
通过使用lambda函数对d排序来创建新字典d1
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
Run Code Online (Sandbox Code Playgroud)
d1应该为{1:89,2:3,3:0,4:5},根据d中的键排序。
Python字典是无序的。通常,这不是问题,因为最常见的用例是进行查找。
执行所需操作的最简单方法是创建collections.OrderedDict
按排序顺序插入元素。
ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])
Run Code Online (Sandbox Code Playgroud)
如上面其他建议那样,如果需要迭代,最简单的方法是迭代排序的键。例子-
打印按键排序的值:
# 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
Run Code Online (Sandbox Code Playgroud)
获取按键排序的值列表:
values = [d[k] for k in sorted(d.keys())]
Run Code Online (Sandbox Code Playgroud)
小智 5
我想出了单行字典排序。
>> 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]
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。
此函数将按其键递归地对任何字典进行排序。也就是说,如果字典中的任何值也是字典,它也将按其键排序。如果您在 CPython 3.6 或更高版本上运行,则可以进行简单的更改以使用 adict
而不是 an 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)
Run Code Online (Sandbox Code Playgroud)