Python 如何按键对词典进行排序?
从Python 如何按键对词典进行排序?,python,sorting,dictionary,Python,Sorting,Dictionary,从{2:3,1:89,4:5,3:0}到{1:89,2:3,3:0,4:5}有什么好办法 我检查了一些帖子,但它们都使用返回元组的“排序”操作符 标准Python字典是无序的。即使您对(键、值)对进行了排序,您也无法将它们存储在dict中以保持排序 最简单的方法是使用,它会记住插入元素的顺序: In [1]: import collections In [2]: d = {2:3, 1:89, 4:5, 3:0} In [3]: od = collections.OrderedDict(so
{2:3,1:89,4:5,3:0}
到{1:89,2:3,3:0,4:5}
有什么好办法
我检查了一些帖子,但它们都使用返回元组的“排序”操作符 标准Python字典是无序的。即使您对(键、值)对进行了排序,您也无法将它们存储在
dict
中以保持排序
最简单的方法是使用,它会记住插入元素的顺序:
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()
:
正如其他人所提到的,字典天生就是无序的。但是,如果问题仅仅是以有序方式显示词典,则可以覆盖词典子类中的
\uuu str\uuu
方法,并使用此词典类而不是内置的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控制台上的显示方式。字典本身并没有这样的有序项,如果您想按某种顺序打印它们等,下面是一些示例:
在Python 2.4及更高版本中:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
>>> 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}
>>>
给出:
alan: 2
bob: 1
carl: 40
danny: 3
(Python低于2.4:)
来源:来源:
在Python3中
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
给予
在这里,我找到了一些最简单的解决方案,可以使用
pprint
按键对python dict进行排序。
例如
但在使用pprint时,它将返回排序后的dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
找到另一种方法:
import json
print json.dumps(d, sort_keys = True)
upd:1.这也会对嵌套对象进行排序(谢谢@DanielF)。
2.python字典是无序的,因此只能打印或分配给str。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())]
获取按键排序的值列表:
# 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())]
有许多Python模块提供字典实现,自动按排序顺序维护键。考虑模块是纯Python和快速AS-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])
简单地说:
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
伙计们,你们把事情搞复杂了。。。这真的很简单
from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)
输出为:
{'A':2,'B':1,'C':3}
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
l=dict.keys()
l2=l
l2.追加(0)
l3=[]
对于范围(0,len(l))内的中继器:
smallnum=float(“inf”)
对于l2中的listitem:
如果listitem
有一种简单的方法可以对字典进行排序
根据你的问题,
解决办法是:
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)]
因此,通过将其更改为键、值和项目,您可以按照您的需要打印。希望这对您有所帮助 最简单的解决方案是,您应该获得一个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]
以下是输出(取消顺序)
将生成您想要的内容:
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}
但这并不是正确的方法,因为它可能会在不同的字典中显示不同的行为,这是我最近学到的。因此,蒂姆在回答我的问题时提出了完美的方法,我在这里分享
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
我认为最简单的方法是按键对dict进行排序,并将排序后的key:value对保存在新dict中
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
对于CPython/pypy3.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}
Python字典在Python 3.6之前是无序的。在Python 3.6的CPython实现中,dictionary保持插入顺序。 从Python3.7开始,这将成为一种语言特性 在Python 3.6()的changelog中: 考虑了这种新实现的保序方面 实施细节,不应依赖(这可能 未来会发生变化,但人们希望有这种新的格言 在更改 语言规范要求对所有当前 以及未来的Python实现;这也有助于保护 与旧版本的语言向后兼容,其中 随机迭代顺序仍然有效,例如Python 3.5) 在Python 3.7()的文档中: 在字典上执行list(d)返回所使用的所有键的列表 在字典中,按插入顺序(如果要排序,只需使用 已排序(d)代替) 因此,与以前的版本不同,您可以在Python 3.6/3.7之后对dict进行排序。如果要对包含子目录在内的嵌套目录进行排序,可以执行以下操作:
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item):
return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict)
您可以根据您的问题按键对当前词典进行排序,从而创建一个新词典 这是你的字典
d = {2:3, 1:89, 4:5, 3:0}
创建一个新的
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
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]}
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item):
return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict)
d = {2:3, 1:89, 4:5, 3:0}
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
>>> 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}
>>>
>> 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]
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)
d = {2:3, 1:89, 4:5, 3:0}
s = {k : d[k] for k in sorted(d)}
s
Out[1]: {1: 89, 2: 3, 3: 0, 4: 5}