In Python, how can you easily retrieve sorted items from a dictionary?
Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
I want to print the associated values in the following sequence sorted by key:
this is a
this is b
this is c
Asked by: Steven651 | Posted: 28-01-2022
Answer 1
Do you mean that you need the values sorted by the value of the key? In that case, this should do it:
for key in sorted(d):
print d[key]
EDIT: changed to use sorted(d) instead of sorted(d.keys()), thanks Eli!
Answered by: First Name110 | Posted: 01-03-2022Answer 2
Or shorter,
for key, value in sorted(d.items()):
print value
Answered by: Anna908 | Posted: 01-03-2022
Answer 3
This snippet will do so. If you're going to do it frequently, you might want to make a 'sortkeys' method or somesuch to make it easier on the eyes.
keys = list(d.keys())
keys.sort()
for key in keys:
print d[key]
Edit: dF's solution is better -- I forgot all about sorted().
Answered by: Stella692 | Posted: 01-03-2022Answer 4
>>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
>>> for k,v in sorted(d.items()):
... print v, k
...
this is a a
this is b b
this is c c
Answered by: Rafael448 | Posted: 01-03-2022
Answer 5
for key in sorted(d):
print d[key]
Answered by: Tess671 | Posted: 01-03-2022
Answer 6
You can also sort a dictionary by value and control the sort order:
import operator
d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}
for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
print key, " ", value
Output:
b this is 3
a this is 2
c this is 1
Answer 7
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
ks = d.keys()
ks.sort()
for k in ks:
print "this is " + k
Answered by: Max290 | Posted: 01-03-2022
Answer 8
Do you mean "sorted" instead of "ordered"? It seems your question aims at sorting a dictionary and not at ordering it. If you do mean "ordered", you can use an OrderedDict from the collections module. Those dictionaries remember the order in which the key/value pairs were entered:
from collections import OrderedDict
Reference information: https://docs.python.org/2/library/collections.html#collections.OrderedDict
Answered by: Victoria876 | Posted: 01-03-2022Similar questions
sorting - Python: retrieve dictionary keys in order as added?
In Python, is there a way to retrieve the list of keys in the order in that the items were added?
String.compareMethods = {'equals': String.equals,
'contains': String.contains,
'startswith': String.startswith,
'endswith': String.endswith}
The keys you see here are meant for a select (dropdown) box so the order is im...
python - How do you retrieve items from a dictionary in the order that they're inserted?
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
How to retrieve a single item from nested dictionary in python
I am reading from a file with data like this:
{"day" :"Monday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Tuesday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Wednesday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Thursday", "alarm":"on", "kids":"School" , "work":"nights"}
{"day" :"Friday", "alarm":"on", "kids":"School" , "work":"nights"}
{"day" :"Saturday", "alarm":"...
sorting - Python: retrieve dictionary keys in order as added?
In Python, is there a way to retrieve the list of keys in the order in that the items were added?
String.compareMethods = {'equals': String.equals,
'contains': String.contains,
'startswith': String.startswith,
'endswith': String.endswith}
The keys you see here are meant for a select (dropdown) box so the order is im...
Python - retrieve info from dictionary list & syntax error
I'm trying to figure out a 'simple' dictionary/database with Python, which will retrieve a name from a list of ten, with the requested information.
i.e. input is 'John phone'; output is 'John's phone number is 0401'.
Apart from being completely stuck on this retrieval of specific information, python has suddenly been giving me a syntax error on the name = raw_input line.
The following is the file i've sa...
python - How to retrieve a variable from a list located in a dictionary, located in a list? two
python - Retrieve first row of csv using dictionary
I am reading a csv file using the csv.DictReader class.
I read on the python documentation that
class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
I tried to get the first row of my csv file using the keys() method of...
python - How to retrieve values from nested dictionary given list of keys?
This question already has answers here:
how to store set of images in a dictionary, and retrieve it using python opencv
i have a dictionary, where i have taken the images as value and indexes as key, i have stored it using zip function, and when am trying to retrieve it, its not displaying the images. what i have done is:
pth = 'D:\6th sem\Major project\Code'
resizedlist = dict()
for infile in glob.glob(os.path.join(path,'*.jpg')):
imge = cv2.imread(infile)
re_img = cv2.resize(imge,(256,256))
ImEdges = cv2.imwrite('...
python - How do I retrieve more than one item pair from a dictionary
Does anyone know how I retrieve two pairs from a dictionary
I'm trying to present data in a more compact format
a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' }
for i,j,k,l in a:
print i, ' - ' ,j , ' , ' ,k, ' - ' ,l
1 - item 1 , 2 - item 2
3 - item 3 , 4 - item 4
edit - sorry ment it to look like above
python - Is there any way to retrieve data from dictionary with a tuple?
Say there is a dictionary and a tuple, I want use the tuple as keys to retrieve values from the dictionary, and then put the result into another tuple.
For example, the dictionary and the tuple are below
dic = {"b": "bad", "a": "alpha", "c": "change"}
tup = ("a", "b", "c"),
and what I want is another tuple: ("alpha", "bad", "change"), is there any appro...
Python dictionary from an object's fields
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
NOTE: It should not include methods. Only fields.
python - How do you retrieve items from a dictionary in the order that they're inserted?
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
python - How can I make a dictionary from separate lists of keys and values?
I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
Into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
python - Dictionary or If statements, Jython
I am writing a script at the moment that will grab certain information from HTML using dom4j.
Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below:
if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
Is a Python dictionary an example of a hash table?
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?
The list sort() method is a modifier function that returns None.
So if I want to iterate through all of the keys in a dictionary I cannot do:
for k in somedictionary.keys().sort():
dosomething()
Instead, I must:
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
Is there a pretty way to iterate t...
python - Interface to versioned dictionary
I have an versioned document store which I want to access through an dict like interface.
Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int).
from UserDict import DictMixin
class VDict(DictMixin):
def __getitem__(self, key):
if isinstance(key, tuple):
docid, rev = key
e...
python - List all words in a dictionary that start with <user input>
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
python - Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?
I want to increment the value if there's already one there, or set it to 1 otherwise:
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
I have a list of variable names, like this:
['foo', 'bar', 'baz']
(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)
How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?
{'foo': foo, 'bar': bar, 'baz': baz}
Now that I'm re-aski...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python