키로 사전을 정렬하려면 어떻게해야합니까?
에서 {2:3, 1:89, 4:5, 3:0}
로 가는 좋은 방법은 무엇입니까 {1:89, 2:3, 3:0, 4:5}
?
일부 게시물을 확인했지만 모두 튜플을 반환하는 "sorted"연산자를 사용합니다.
표준 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
파이썬 3
Python 3 사용자의 경우 다음 .items()
대신 을 사용해야합니다 .iteritems()
.
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
사전 자체에는 순서가 지정된 항목이 없습니다. 인쇄하려는 경우 등을 순서대로 인쇄하려면 여기에 몇 가지 예가 있습니다.
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/
>>> 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)])
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}
정렬 된 순서로 키를 자동으로 유지하는 사전 구현을 제공하는 여러 Python 모듈이 있습니다. pure-Python 및 fast-as-C 구현 인 sortedcontainers 모듈을 고려하십시오 . 또한 서로 벤치마킹 된 다른 인기 옵션과 의 성능 비교 도 있습니다.
반복하는 동안 키 / 값 쌍을 지속적으로 추가 및 제거해야하는 경우 정렬 된 사전을 사용하는 것은 부적절한 솔루션입니다.
>>> 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
다른 사람들이 언급했듯이 사전은 본질적으로 순서가 없습니다. 그러나 문제가 단순히 정렬 된 방식으로 사전을 표시하는 것이라면 __str__
사전 하위 클래스 의 메서드를 재정의 하고 builtin 대신이 사전 클래스를 사용할 수 있습니다 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 콘솔에 표시되는 방법에 대해서는 아무것도 변경하지 않습니다 .
다른 방법을 찾았습니다.
import json
print json.dumps(d, sort_keys = True)
upd :
1. 이것은 또한 중첩 된 개체를 정렬합니다 (@DanielF에게 감사드립니다).
2. 파이썬 사전은 순서가 지정되어 있지 않으므로 인쇄 또는 str에만 할당하기에 적합합니다.
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
Python 3.6 이전에는 Python 사전이 순서가 지정되지 않았습니다. 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 이후에 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)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
여기에서 .NET을 사용하여 키별로 파이썬 사전을 정렬하는 가장 간단한 솔루션을 찾았습니다 pprint
. 예.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
그러나 pprint를 사용하는 동안 정렬 된 dict를 반환합니다.
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
사전을 정렬하는 쉬운 방법이 있습니다.
귀하의 질문에 따르면
해결책은 다음과 같습니다.
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를 키별로 정렬하고 정렬 된 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
원하는 것을 정확하게 생성합니다.
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]))
파이썬 딕셔너리는 순서가 없습니다. 일반적으로 가장 일반적인 사용 사례는 조회를 수행하는 것이므로 문제가되지 않습니다.
원하는 작업을 수행하는 가장 간단한 방법 collections.OrderedDict
은 정렬 된 순서로 요소를 삽입하는 것입니다.
ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])
If you need to iterated, as others above have suggested, the simplest way would be to iterate over sorted keys. Examples-
Print values sorted by 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
Get list of values sorted by keys:
values = [d[k] for k in sorted(d.keys())]
You can create a new dictionary by sorting the current dictionary by key as per your question.
This is your dictionary
d = {2:3, 1:89, 4:5, 3:0}
Create a new dictionary d1 by sorting this d using lambda function
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
d1 should be {1: 89, 2: 3, 3: 0, 4: 5}, sorted based on keys in d.
I come up with single line dict sorting.
>> 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]
Hope this will be helpful.
Guys you are making things complicated ... it's really simple
from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)
The output is:
{'A':2,'B':1,'C':3}
Simplest solution is that you should get a list of dict key is sorted order and then iterate over dict. For example
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]
Following will be the output (desending order)
e 30
b 13
d 4
c 2
a 1
A timing comparison of the two methods in 2.7 shows them to be virtually identical:
>>> 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
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)
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]}
Or use pandas
,
Demo:
>>> 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}
>>>
See:
This function will sort any dictionary recursively by its key. That is, if any value in the dictionary is also a dictionary, it too will be sorted by its key. If you are running on CPython 3.6 or greater, than a simple change to use a dict
rather than an OrderedDict
can be made.
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)
Another pythonic approach would be
def sort_dict(my_dict):
return sorted(my_dict.items(), key=lambda x :x[1])
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)
참고URL : https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key
'Programing' 카테고리의 다른 글
파이썬 프로그램 실행 시간을 어떻게 얻습니까? (0) | 2020.09.29 |
---|---|
시간 초과로 Redux 작업을 전달하는 방법은 무엇입니까? (0) | 2020.09.29 |
forEach 루프와 함께 async / await 사용 (0) | 2020.09.29 |
CommonJS, AMD 및 RequireJS 간의 관계? (0) | 2020.09.29 |
푸시되지 않은 git 커밋을 어떻게 삭제합니까? (0) | 2020.09.29 |