如何根据字典的键进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
如何根据字典的键进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
一个简单的方法来实现这个:
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}
在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
我发现一个简单的方法可以对字典进行排序,就是创建一个新的字典,基于你想要排序的字典的键值对进行排序。
如果你想要对 dict = {}
进行排序,使用相关的方法检索所有项目,使用 sorted()
函数对其进行排序,然后创建新的字典。
这里是使用字典推导式的代码:
sorted_dict = {k:v for k,v in sorted(dict.items())}
根据您的问题,您可以通过按键对当前字典进行排序来创建一个新字典。
这是您的字典
d = {2:3, 1:89, 4:5, 3:0}
使用 lambda 函数对这个字典进行排序,创建一个新的名为 d1 的字典。
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
根据 d 的键按顺序排序,d1 应为 {1: 89, 2: 3, 3: 0, 4: 5}。
d1 = dict(sorted(d.items()))
就能正常运作。 - M.Vanderlee有一种简单的方法可以对字典进行排序。
根据你的问题,
解决方案是:
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)]
因此,通过将其转换为键、值和项,您可以像您想要的那样进行打印。希望这可以帮助您!我在这里找到了一些使用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}
以下是建议方案的性能表现:
from collections import OrderedDict
from sortedcontainers import SortedDict
import json
keys = np.random.rand(100000)
vals = np.random.rand(100000)
d = dict(zip(keys, vals))
timeit SortedDict(d)
#45.8 ms ± 780 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit sorted(d.items())
#91.9 ms ± 707 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit OrderedDict(sorted(d.items(), key=lambda x: x[0]))
#93.7 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit dict(sorted(dic.items()))
#113 ms ± 824 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit OrderedDict(sorted(dic.items()))
#122 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit json.dumps(d, sort_keys=True)
#259 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
从我们看到的情况来看,Grant Jenks的解决方案是目前最快的。
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在我的查询响应中提出了完美的方法,我在这里分享。
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[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
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
我提出了一种单行字典排序方法。
>> 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]
TreeMap
(https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html),它的行为完全符合OP的要求。 - Nayuki