python read file into dictionary [duplicate] - python

How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}

Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
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)])
Never mind the way od is printed out; it'll work as expected:
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
For Python 3 users, one needs to use the .items() instead of .iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5

Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:
In Python 2.4 and above:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
gives:
alan: 2
bob: 1
carl: 40
danny: 3
(Python below 2.4:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}

From Python's collections library documentation:
>>> 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)])

There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.
Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.
>>> 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)]
The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])

Simply:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
Output:
1 89
2 3
3 0
4 5

Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, the dictionary keeps the insertion order.
From Python 3.7, this will become a language feature.
In changelog of Python 3.6 (https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
The order-preserving aspect of this new implementation is considered
an implementation detail and should not be relied upon (this may
change in the future, but it is desired to have this new dict
implementation in the language for a few releases before changing the
language spec to mandate order-preserving semantics for all current
and future Python implementations; this also helps preserve
backward-compatibility with older versions of the language where
random iteration order is still in effect, e.g. Python 3.5).
In the document of Python 3.7 (https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
Performing list(d) on a dictionary returns a list of all the keys used
in the dictionary, in insertion order (if you want it sorted, just use
sorted(d) instead).
So unlike previous versions, you can sort a dict after Python 3.6/3.7. If you want to sort a nested dict including the sub-dict inside, you can do:
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)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

Found another way:
import json
print json.dumps(d, sort_keys = True)
upd:
1. this also sorts nested objects (thanks #DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.

As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.
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}
Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.

An easy way to do this:
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}

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

There are plenty of answers here already showcasing popular ways to sort a Python dictionary. I thought I'd add a few more less-obvious ways for those coming here from Google looking for non-standard ideas.
Sample Dictionary: d = {2: 'c', 1: 'b', 0: 'a', 3: 'd'}
Dictionary Comprehension
# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}
Using Lambdas
Sorting isn't always intended to order strictly in ascending or descending order. For more conditional sorting, use the above method combined with lamdas:
{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}
More Examples
This thread is already full enough of good examples. For some more examples, as well as edge-cases and oddities check out this article on sorting dictionaries in Python.

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.

A simple way I found to sort a dictionary is to create a new one, based on the sorted key:value items of the one you're trying to sort.
If you want to sort dict = {}, retrieve all its items using the associated method, sort them using the sorted() function then create the new dictionary.
Here's the code using dictionary comprehension :
sorted_dict = {k:v for k,v in sorted(dict.items())}

Here I found some simplest solution to sort the python dict by key using pprint.
eg.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
but while using pprint it will return sorted dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

There is an easy way to sort a dictionary.
According to your question,
The solution is :
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(Where c,is the name of your dictionary.)
This program gives the following output:
[(1, 89), (2, 3), (3, 0), (4, 5)]
like u wanted.
Another example is:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Gives the output:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Gives the output:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!

Will generate exactly what you want:
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}
But this is not the correct way to do this, because, It could show a distinct behavior with different dictionaries, which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

Here is the performance of the suggested solutions:
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)
As we see, Grant Jenks's solution is by far the fastest.

I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new 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]
To make it clearer:
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

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.

Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.
The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.
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())]

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)

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

For the way how question is formulated, the most answers here are answering it correctly.
However, considering how the things should be really done, taking to acount decades and decades of computer science, it comes to my total suprise that there is actually only one answer here (from GrantJ user) suggesting usage of sorted associative containers (sortedcontainers) which sorts elements based on key at their insertions point.
That will avoid massive performance impact per each calling of sort(...) (at minimum O(N*log(N)), where N is in number of elements (logically, this applies for all such solutions here which suggest to use the sort(...)). Take to account that for all such solutions, the sort(...) will need to be called every time when colletion needs to be accessed as sorted AFTER it was modified by adding/removing elements ...

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}

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]}

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

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:
Docs of this
Documentation of whole pandas

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)

Related

How do i sort a dictionnary by a custom order of values [duplicate]

I'm working on python 3.2.2.
Breaking my head more than 3 hours to sort a dictionary by it's keys.
I managed to make it a sorted list with 2 argument members, but can not make it a sorted dictionary in the end.
This is what I've figured:
myDic={10: 'b', 3:'a', 5:'c'}
sorted_list=sorted(myDic.items(), key=lambda x: x[0])
But no matter what I can not make a dictionary out of this sorted list. How do I do that? Thanks!
A modern and fast solution, for Python 3.7. May also work in some interpreters of Python 3.6.
TLDR
To sort a dictionary by keys use:
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
Almost three times faster than the accepted answer; probably more when you include imports.
Comment on the accepted answer
The example in the accepted answer instead of iterating over the keys only - with key parameter of sorted() or the default behaviour of dict iteration - iterates over tuples (key, value), which suprisingly turns out to be much slower than comparing the keys only and accessing dictionary elements in a list comprehension.
How to sort by key in Python 3.7
The big change in Python 3.7 is that the dictionaries are now ordered by default.
You can generate sorted dict using dict comprehensions.
Using OrderedDict might still be preferable for the compatibility sake.
Do not use sorted(d.items()) without key.
See:
disordered = {10: 'b', 3: 'a', 5: 'c'}
# sort keys, then get values from original - fast
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
# key = itemgetter - slower
from operator import itemgetter
key = itemgetter(0)
sorted_dict = {k: v for k, v in sorted(disordered.items(), key=key)}
# key = lambda - the slowest
key = lambda item: item[0]
sorted_dict = {k: v for k in sorted(disordered.items(), key=key)}
Timing results:
Best for {k: d[k] for k in sorted(d)}: 7.507327548999456
Best for {k: v for k, v in sorted(d.items(), key=key_getter)}: 12.031082626002899
Best for {k: v for k, v in sorted(d.items(), key=key_lambda)}: 14.22885995300021
Best for dict(sorted(d.items(), key=key_getter)): 11.209122000000207
Best for dict(sorted(d.items(), key=key_lambda)): 13.289728325995384
Best for dict(sorted(d.items())): 14.231471302999125
Best for OrderedDict(sorted(d.items(), key=key_getter)): 16.609151654003654
Best for OrderedDict(sorted(d.items(), key=key_lambda)): 18.52622927199991
Best for OrderedDict(sorted(d.items())): 19.436101284998585
Testing code:
from timeit import repeat
setup_code = """
from operator import itemgetter
from collections import OrderedDict
import random
random.seed(0)
d = {i: chr(i) for i in [random.randint(0, 120) for repeat in range(120)]}
key_getter = itemgetter(0)
key_lambda = lambda item: item[0]
"""
cases = [
# fast
'{k: d[k] for k in sorted(d)}',
'{k: v for k, v in sorted(d.items(), key=key_getter)}',
'{k: v for k, v in sorted(d.items(), key=key_lambda)}',
# slower
'dict(sorted(d.items(), key=key_getter))',
'dict(sorted(d.items(), key=key_lambda))',
'dict(sorted(d.items()))',
# the slowest
'OrderedDict(sorted(d.items(), key=key_getter))',
'OrderedDict(sorted(d.items(), key=key_lambda))',
'OrderedDict(sorted(d.items()))',
]
for code in cases:
times = repeat(code, setup=setup_code, repeat=3)
print(f"Best for {code}: {min(times)}")
dict does not keep its elements' order. What you need is an OrderedDict: http://docs.python.org/library/collections.html#collections.OrderedDict
edit
Usage example:
>>> from collections import OrderedDict
>>> a = {'foo': 1, 'bar': 2}
>>> a
{'foo': 1, 'bar': 2}
>>> b = OrderedDict(sorted(a.items()))
>>> b
OrderedDict([('bar', 2), ('foo', 1)])
>>> b['foo']
1
>>> b['bar']
2
I don't think you want an OrderedDict. It sounds like you'd prefer a SortedDict, that is a dict that maintains its keys in sorted order. The sortedcontainers module provides just such a data type. It's written in pure-Python, fast-as-C implementations, has 100% coverage and hours of stress.
Installation is easy with pip:
pip install sortedcontainers
Note that if you can't pip install then you can simply pull the source files from the open-source repository.
Then you're code is simply:
from sortedcontainers import SortedDict
myDic = SortedDict({10: 'b', 3:'a', 5:'c'})
sorted_list = list(myDic.keys())
The sortedcontainers module also maintains a performance comparison with other popular implementations.
Python's ordinary dicts cannot be made to provide the keys/elements in any specific order. For that, you could use the OrderedDict type from the collections module. Note that the OrderedDict type merely keeps a record of insertion order. You would have to sort the entries prior to initializing the dictionary if you want subsequent views/iterators to return the elements in order every time. For example:
>>> myDic={10: 'b', 3:'a', 5:'c'}
>>> sorted_list=sorted(myDic.items(), key=lambda x: x[0])
>>> myOrdDic = OrderedDict(sorted_list)
>>> myOrdDic.items()
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> myOrdDic[7] = 'd'
>>> myOrdDic.items()
[(3, 'a'), (5, 'c'), (10, 'b'), (7, 'd')]
If you want to maintain proper ordering for newly added items, you really need to use a different data structure, e.g., a binary tree/heap. This approach of building a sorted list and using it to initialize a new OrderedDict() instance is just woefully inefficient unless your data is completely static.
Edit: So, if the object of sorting the data is merely to print it in order, in a format resembling a python dict object, something like the following should suffice:
def pprint_dict(d):
strings = []
for k in sorted(d.iterkeys()):
strings.append("%d: '%s'" % (k, d[k]))
return '{' + ', '.join(strings) + '}'
Note that this function is not flexible w/r/t the types of the key, value pairs (i.e., it expects the keys to be integers and the corresponding values to be strings). If you need more flexibility, use something like strings.append("%s: %s" % (repr(k), repr(d[k]))) instead.
With Python 3.7 I could do this:
>>> myDic={10: 'b', 3:'a', 5:'c'}
>>> sortDic = sorted(myDic.items())
>>> print(dict(sortDic))
{3:'a', 5:'c', 10: 'b'}
If you want a list of tuples:
>>> myDic={10: 'b', 3:'a', 5:'c'}
>>> sortDic = sorted(myDic.items())
>>> print(sortDic)
[(3, 'a'), (5, 'c'), (10, 'b')]
Dictionaries are unordered by definition, What would be the main reason for ordering by key? A list of tuples created by the sort method can be used for whatever the need may have been, but changing the list of tuples back into a dictionary will return a random order
>>> myDic
{10: 'b', 3: 'a', 5: 'c'}
>>> sorted(myDic.items())
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> print(dict(myDic.items()))
{10: 'b', 3: 'a', 5: 'c'}
Maybe not that good but I've figured this:
def order_dic(dic):
ordered_dic={}
key_ls=sorted(dic.keys())
for key in key_ls:
ordered_dic[key]=dic[key]
return ordered_dic
Any modern solution to this problem?
I worked around it with:
order = sorted([ job['priority'] for job in self.joblist ])
sorted_joblist = []
while order:
min_priority = min(order)
for job in self.joblist:
if job['priority'] == min_priority:
sorted_joblist += [ job ]
order.remove(min_priority)
self.joblist = sorted_joblist
The joblist is formatted as:
joblist = [ { 'priority' : 3, 'name' : 'foo', ... }, { 'priority' : 1, 'name' : 'bar', ... } ]
Basically I create a list (order) with all the elements by which I want to sort the dict
then I iterate this list and the dict, when I find the item on the dict I send it to a new dict and remove the item from 'order'.
Seems to be working, but I suppose there are better solutions.
I'm not sure whether this could help, but I had a similar problem and I managed to solve it, by defining an apposite function:
def sor_dic_key(diction):
lista = []
diction2 = {}
for x in diction:
lista.append([x, diction[x]])
lista.sort(key=lambda x: x[0])
for l in lista:
diction2[l[0]] = l[1]
return diction2
This function returns another dictionary with the same keys and relative values, but sorted by its keys.
Similarly, I defined a function that could sort a dictionary by its values. I just needed to use x[1] instead of x[0] in the lambda function. I find this second function mostly useless, but one never can tell!
I like python numpy for this kind of stuff! eg:
r=readData()
nsorted = np.lexsort((r.calls, r.slow_requests, r.very_slow_requests, r.stalled_requests))
I have an example of importing CSV data into a numpy and ordering by column priorities.
https://github.com/unixunion/toolbox/blob/master/python/csv-numpy.py
Kegan
The accepted answer definitely works, but somehow miss an important point.
The OP is asking for a dictionary sorted by it's keys this is just not really possible and not what OrderedDict is doing.
OrderedDict is maintaining the content of the dictionary in insertion order. First item inserted, second item inserted, etc.
>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d
OrderedDict([('foo', 1), ('bar', 2)])
>>> d = OrderedDict()
>>> d['bar'] = 2
>>> d['foo'] = 1
>>> d
OrderedDict([('bar', 2), ('foo', 1)])
Hencefore I won't really be able to sort the dictionary inplace, but merely to create a new dictionary where insertion order match key order. This is explicit in the accepted answer where the new dictionary is b.
This may be important if you are keeping access to dictionaries through containers. This is also important if you itend to change the dictionary later by adding or removing items: they won't be inserted in key order but at the end of dictionary.
>>> d = OrderedDict({'foo': 5, 'bar': 8})
>>> d
OrderedDict([('foo', 5), ('bar', 8)])
>>> d['alpha'] = 2
>>> d
OrderedDict([('foo', 5), ('bar', 8), ('alpha', 2)])
Now, what does mean having a dictionary sorted by it's keys ? That makes no difference when accessing elements by keys, this only matter when you are iterating over items. Making that a property of the dictionary itself seems like overkill. In many cases it's enough to sort keys() when iterating.
That means that it's equivalent to do:
>>> d = {'foo': 5, 'bar': 8}
>>> for k,v in d.iteritems(): print k, v
on an hypothetical sorted by key dictionary or:
>>> d = {'foo': 5, 'bar': 8}
>>> for k, v in iter((k, d[k]) for k in sorted(d.keys())): print k, v
Of course it is not hard to wrap that behavior in an object by overloading iterators and maintaining a sorted keys list. But it is likely overkill.
Sorting dictionaries by value using comprehensions. I think it's nice as 1 line and no need for functions or lambdas
a = {'b':'foo', 'c':'bar', 'e': 'baz'}
a = {f:a[f] for f in sorted(a, key=a.__getitem__)}
Easy and straightforward way:
op = {'1': (1,0,6),'3': (0,45,8),'2': (2,34,10)}
lp3 = sorted(op.items(), key=operator.itemgetter(0), reverse=True)
print(lp3)
ref: https://blog.csdn.net/weixin_37922873/article/details/81210032

Array access to python dictionary [duplicate]

I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
Now, ideally I'd like to be able to do this:
>>> d[l]
{1:2, 5:6}
... but that's not working, since it will look for a key matching the tuple (1,5), the same as d[1,5].
d{1,5} isn't even valid Python (as far as I can tell ...), though it might be handy: The curly braces suggest an unordered set or a dictionary, so returning a dictionary containing the specified keys would look very plausible to me.
d[{1,5}] would also make sense ("here's a set of keys, give me the matching items"), and {1, 5} is an unhashable set, so there can't be a key that matches it -- but of course it throws an error, too.
I know I can do this:
>>> dict([(key, value) for key,value in d.iteritems() if key in l])
{1: 2, 5: 6}
or this:
>>> dict([(key, d[key]) for key in l])
which is more compact
... but I feel there must be a "better" way of doing this. Am I missing a more elegant solution?
(I'm using Python 2.7)
On Python 3 you can use the itertools islice to slice the dict.items() iterator
import itertools
d = {1: 2, 3: 4, 5: 6}
dict(itertools.islice(d.items(), 2))
{1: 2, 3: 4}
Note: this solution does not take into account specific keys. It slices by internal ordering of d, which in Python 3.7+ is guaranteed to be insertion-ordered.
You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:
print({k:d[k] for k in l if k in d})
Some timings:
{k:d[k] for k in set(d).intersection(l)}
In [22]: %%timeit
l = xrange(100000)
{k:d[k] for k in l}
....:
100 loops, best of 3: 11.5 ms per loop
In [23]: %%timeit
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
....:
10 loops, best of 3: 20.4 ms per loop
In [24]: %%timeit
l = xrange(100000)
l = set(l)
{key: d[key] for key in d.viewkeys() & l}
....:
10 loops, best of 3: 24.7 ms per
In [25]: %%timeit
l = xrange(100000)
{k:d[k] for k in l if k in d}
....:
100 loops, best of 3: 17.9 ms per loop
I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.
To slice a dictionary, Convert it to a list of tuples using d.items(), slice the list and create a dictionary out of it.
Here.
d = {1:2, 3:4, 5:6, 7:8}
To get the first 2 items
first_two = dict(list(d.items())[:2])
first_two
{1: 2, 3: 4}
Use a set to intersect on the dict.viewkeys() dictionary view:
l = {1, 5}
{key: d[key] for key in d.viewkeys() & l}
This is Python 2 syntax, in Python 3 use d.keys().
This still uses a loop, but at least the dictionary comprehension is a lot more readable. Using set intersections is very efficient, even if d or l is large.
Demo:
>>> d = {1:2, 3:4, 5:6, 7:8}
>>> l = {1, 5}
>>> {key: d[key] for key in d.viewkeys() & l}
{1: 2, 5: 6}
Write a dict subclass that accepts a list of keys as an "item" and returns a "slice" of the dictionary:
class SliceableDict(dict):
default = None
def __getitem__(self, key):
if isinstance(key, list): # use one return statement below
# uses default value if a key does not exist
return {k: self.get(k, self.default) for k in key}
# raises KeyError if a key does not exist
return {k: self[k] for k in key}
# omits key if it does not exist
return {k: self[k] for k in key if k in self}
return dict.get(self, key)
Usage:
d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d[[1, 5]] # {1: 2, 5: 6}
Or if you want to use a separate method for this type of access, you can use * to accept any number of arguments:
class SliceableDict(dict):
def slice(self, *keys):
return {k: self[k] for k in keys}
# or one of the others from the first example
d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d.slice(1, 5) # {1: 2, 5: 6}
keys = 1, 5
d.slice(*keys) # same
set intersection and dict comprehension can be used here
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}
the dictionary
d = {1:2, 3:4, 5:6, 7:8}
the subset of keys I'm interested in
l = (1,5)
answer
{key: d[key] for key in l}
Another option is to convert the dictionary into a pandas Series object and then locating the specified indexes:
>>> d = {1:2, 3:4, 5:6, 7:8}
>>> l = [1,5]
>>> import pandas as pd
>>> pd.Series(d).loc[l].to_dict()
{1: 2, 5: 6}
My case is probably relatively uncommon, but, I'm posting it here nonetheless in case it helps someone (though not OP directly).
I came across this question searching how to slice a dictionary that had item counts. Basically I had a dictionary where the keys were letters, and the values were the number of times the letter appeared (i.e. abababc --> {'a': 3, 'b': 3, 'c': 1} I wanted to 'slice' the dictionary so that I could return the most common n keys.
It turns out that this is exactly what a Collections Counter object is for, and instead of needing to 'slice' my dictionary, I could easily just convert it to a collections.Counter and then call most_common(n): https://docs.python.org/3/library/collections.html#collections.Counter.most_common
You can do slicing of the dictionary with the help of the module dictionarify
This is the link for documentation-https://github.com/suryavenom/Flexi/blob/main/README.md.
Installation -
pip install dictionarify

Sort a dict in Python [duplicate]

How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}
Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
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)])
Never mind the way od is printed out; it'll work as expected:
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
For Python 3 users, one needs to use the .items() instead of .iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:
In Python 2.4 and above:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
gives:
alan: 2
bob: 1
carl: 40
danny: 3
(Python below 2.4:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
From Python's collections library documentation:
>>> 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)])
There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.
Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.
>>> 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)]
The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
Simply:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
Output:
1 89
2 3
3 0
4 5
Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, the dictionary keeps the insertion order.
From Python 3.7, this will become a language feature.
In changelog of Python 3.6 (https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
The order-preserving aspect of this new implementation is considered
an implementation detail and should not be relied upon (this may
change in the future, but it is desired to have this new dict
implementation in the language for a few releases before changing the
language spec to mandate order-preserving semantics for all current
and future Python implementations; this also helps preserve
backward-compatibility with older versions of the language where
random iteration order is still in effect, e.g. Python 3.5).
In the document of Python 3.7 (https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
Performing list(d) on a dictionary returns a list of all the keys used
in the dictionary, in insertion order (if you want it sorted, just use
sorted(d) instead).
So unlike previous versions, you can sort a dict after Python 3.6/3.7. If you want to sort a nested dict including the sub-dict inside, you can do:
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)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
Found another way:
import json
print json.dumps(d, sort_keys = True)
upd:
1. this also sorts nested objects (thanks #DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.
As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.
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}
Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.
An easy way to do this:
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}
In Python 3.
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
gives
1 89
2 3
3 0
4 5
There are plenty of answers here already showcasing popular ways to sort a Python dictionary. I thought I'd add a few more less-obvious ways for those coming here from Google looking for non-standard ideas.
Sample Dictionary: d = {2: 'c', 1: 'b', 0: 'a', 3: 'd'}
Dictionary Comprehension
# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}
Using Lambdas
Sorting isn't always intended to order strictly in ascending or descending order. For more conditional sorting, use the above method combined with lamdas:
{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}
More Examples
This thread is already full enough of good examples. For some more examples, as well as edge-cases and oddities check out this article on sorting dictionaries in Python.
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.
A simple way I found to sort a dictionary is to create a new one, based on the sorted key:value items of the one you're trying to sort.
If you want to sort dict = {}, retrieve all its items using the associated method, sort them using the sorted() function then create the new dictionary.
Here's the code using dictionary comprehension :
sorted_dict = {k:v for k,v in sorted(dict.items())}
Here I found some simplest solution to sort the python dict by key using pprint.
eg.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
but while using pprint it will return sorted dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
There is an easy way to sort a dictionary.
According to your question,
The solution is :
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(Where c,is the name of your dictionary.)
This program gives the following output:
[(1, 89), (2, 3), (3, 0), (4, 5)]
like u wanted.
Another example is:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Gives the output:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Gives the output:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!
Will generate exactly what you want:
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}
But this is not the correct way to do this, because, It could show a distinct behavior with different dictionaries, which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
Here is the performance of the suggested solutions:
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)
As we see, Grant Jenks's solution is by far the fastest.
I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new 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]
To make it clearer:
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
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.
Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.
The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.
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())]
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)
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
For the way how question is formulated, the most answers here are answering it correctly.
However, considering how the things should be really done, taking to acount decades and decades of computer science, it comes to my total suprise that there is actually only one answer here (from GrantJ user) suggesting usage of sorted associative containers (sortedcontainers) which sorts elements based on key at their insertions point.
That will avoid massive performance impact per each calling of sort(...) (at minimum O(N*log(N)), where N is in number of elements (logically, this applies for all such solutions here which suggest to use the sort(...)). Take to account that for all such solutions, the sort(...) will need to be called every time when colletion needs to be accessed as sorted AFTER it was modified by adding/removing elements ...
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}
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]}
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
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:
Docs of this
Documentation of whole pandas
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)

Workaround dictionary sorting [duplicate]

How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}
Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
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)])
Never mind the way od is printed out; it'll work as expected:
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
For Python 3 users, one needs to use the .items() instead of .iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:
In Python 2.4 and above:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
gives:
alan: 2
bob: 1
carl: 40
danny: 3
(Python below 2.4:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
From Python's collections library documentation:
>>> 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)])
There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.
Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.
>>> 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)]
The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
Simply:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
Output:
1 89
2 3
3 0
4 5
Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, the dictionary keeps the insertion order.
From Python 3.7, this will become a language feature.
In changelog of Python 3.6 (https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
The order-preserving aspect of this new implementation is considered
an implementation detail and should not be relied upon (this may
change in the future, but it is desired to have this new dict
implementation in the language for a few releases before changing the
language spec to mandate order-preserving semantics for all current
and future Python implementations; this also helps preserve
backward-compatibility with older versions of the language where
random iteration order is still in effect, e.g. Python 3.5).
In the document of Python 3.7 (https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
Performing list(d) on a dictionary returns a list of all the keys used
in the dictionary, in insertion order (if you want it sorted, just use
sorted(d) instead).
So unlike previous versions, you can sort a dict after Python 3.6/3.7. If you want to sort a nested dict including the sub-dict inside, you can do:
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)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
Found another way:
import json
print json.dumps(d, sort_keys = True)
upd:
1. this also sorts nested objects (thanks #DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.
As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.
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}
Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.
An easy way to do this:
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}
In Python 3.
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
gives
1 89
2 3
3 0
4 5
There are plenty of answers here already showcasing popular ways to sort a Python dictionary. I thought I'd add a few more less-obvious ways for those coming here from Google looking for non-standard ideas.
Sample Dictionary: d = {2: 'c', 1: 'b', 0: 'a', 3: 'd'}
Dictionary Comprehension
# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}
Using Lambdas
Sorting isn't always intended to order strictly in ascending or descending order. For more conditional sorting, use the above method combined with lamdas:
{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}
More Examples
This thread is already full enough of good examples. For some more examples, as well as edge-cases and oddities check out this article on sorting dictionaries in Python.
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.
A simple way I found to sort a dictionary is to create a new one, based on the sorted key:value items of the one you're trying to sort.
If you want to sort dict = {}, retrieve all its items using the associated method, sort them using the sorted() function then create the new dictionary.
Here's the code using dictionary comprehension :
sorted_dict = {k:v for k,v in sorted(dict.items())}
Here I found some simplest solution to sort the python dict by key using pprint.
eg.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
but while using pprint it will return sorted dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
There is an easy way to sort a dictionary.
According to your question,
The solution is :
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(Where c,is the name of your dictionary.)
This program gives the following output:
[(1, 89), (2, 3), (3, 0), (4, 5)]
like u wanted.
Another example is:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Gives the output:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Gives the output:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!
Will generate exactly what you want:
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}
But this is not the correct way to do this, because, It could show a distinct behavior with different dictionaries, which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
Here is the performance of the suggested solutions:
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)
As we see, Grant Jenks's solution is by far the fastest.
I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new 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]
To make it clearer:
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
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.
Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.
The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.
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())]
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)
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
For the way how question is formulated, the most answers here are answering it correctly.
However, considering how the things should be really done, taking to acount decades and decades of computer science, it comes to my total suprise that there is actually only one answer here (from GrantJ user) suggesting usage of sorted associative containers (sortedcontainers) which sorts elements based on key at their insertions point.
That will avoid massive performance impact per each calling of sort(...) (at minimum O(N*log(N)), where N is in number of elements (logically, this applies for all such solutions here which suggest to use the sort(...)). Take to account that for all such solutions, the sort(...) will need to be called every time when colletion needs to be accessed as sorted AFTER it was modified by adding/removing elements ...
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}
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]}
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
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:
Docs of this
Documentation of whole pandas
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)

How to sort ascending the dictionary [duplicate]

How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}
Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
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)])
Never mind the way od is printed out; it'll work as expected:
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
For Python 3 users, one needs to use the .items() instead of .iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:
In Python 2.4 and above:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
gives:
alan: 2
bob: 1
carl: 40
danny: 3
(Python below 2.4:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
From Python's collections library documentation:
>>> 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)])
There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There is also a performance comparison with other popular options benchmarked against one another.
Using an ordered dict is an inadequate solution if you need to constantly add and remove key/value pairs while also iterating.
>>> 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)]
The SortedDict type also supports indexed location lookups and deletion which isn't possible with the built-in dict type.
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
Simply:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
Output:
1 89
2 3
3 0
4 5
Python dictionary was unordered before Python 3.6. In CPython implementation of Python 3.6, the dictionary keeps the insertion order.
From Python 3.7, this will become a language feature.
In changelog of Python 3.6 (https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
The order-preserving aspect of this new implementation is considered
an implementation detail and should not be relied upon (this may
change in the future, but it is desired to have this new dict
implementation in the language for a few releases before changing the
language spec to mandate order-preserving semantics for all current
and future Python implementations; this also helps preserve
backward-compatibility with older versions of the language where
random iteration order is still in effect, e.g. Python 3.5).
In the document of Python 3.7 (https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
Performing list(d) on a dictionary returns a list of all the keys used
in the dictionary, in insertion order (if you want it sorted, just use
sorted(d) instead).
So unlike previous versions, you can sort a dict after Python 3.6/3.7. If you want to sort a nested dict including the sub-dict inside, you can do:
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)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
Found another way:
import json
print json.dumps(d, sort_keys = True)
upd:
1. this also sorts nested objects (thanks #DanielF).
2. python dictionaries are unordered therefore this is sutable for print or assign to str only.
As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the __str__ method in a dictionary subclass, and use this dictionary class rather than the builtin dict. Eg.
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}
Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with print or at the python console.
An easy way to do this:
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}
In Python 3.
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
gives
1 89
2 3
3 0
4 5
There are plenty of answers here already showcasing popular ways to sort a Python dictionary. I thought I'd add a few more less-obvious ways for those coming here from Google looking for non-standard ideas.
Sample Dictionary: d = {2: 'c', 1: 'b', 0: 'a', 3: 'd'}
Dictionary Comprehension
# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}
Using Lambdas
Sorting isn't always intended to order strictly in ascending or descending order. For more conditional sorting, use the above method combined with lamdas:
{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}
More Examples
This thread is already full enough of good examples. For some more examples, as well as edge-cases and oddities check out this article on sorting dictionaries in Python.
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.
A simple way I found to sort a dictionary is to create a new one, based on the sorted key:value items of the one you're trying to sort.
If you want to sort dict = {}, retrieve all its items using the associated method, sort them using the sorted() function then create the new dictionary.
Here's the code using dictionary comprehension :
sorted_dict = {k:v for k,v in sorted(dict.items())}
Here I found some simplest solution to sort the python dict by key using pprint.
eg.
>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99}
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
but while using pprint it will return sorted dict
>>> import pprint
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
There is an easy way to sort a dictionary.
According to your question,
The solution is :
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(Where c,is the name of your dictionary.)
This program gives the following output:
[(1, 89), (2, 3), (3, 0), (4, 5)]
like u wanted.
Another example is:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Gives the output:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Gives the output:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!
Will generate exactly what you want:
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}
But this is not the correct way to do this, because, It could show a distinct behavior with different dictionaries, which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
Here is the performance of the suggested solutions:
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)
As we see, Grant Jenks's solution is by far the fastest.
I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new 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]
To make it clearer:
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
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.
Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.
The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.
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())]
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)
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
For the way how question is formulated, the most answers here are answering it correctly.
However, considering how the things should be really done, taking to acount decades and decades of computer science, it comes to my total suprise that there is actually only one answer here (from GrantJ user) suggesting usage of sorted associative containers (sortedcontainers) which sorts elements based on key at their insertions point.
That will avoid massive performance impact per each calling of sort(...) (at minimum O(N*log(N)), where N is in number of elements (logically, this applies for all such solutions here which suggest to use the sort(...)). Take to account that for all such solutions, the sort(...) will need to be called every time when colletion needs to be accessed as sorted AFTER it was modified by adding/removing elements ...
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}
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]}
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
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:
Docs of this
Documentation of whole pandas
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)

Categories

Resources