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 through these keys in sorted order without having to break it up in to multiple steps?
Asked by: Roman901 | Posted: 28-01-2022
Answer 1
for k in sorted(somedictionary.keys()):
doSomething(k)
Note that you can also get all of the keys and values sorted by keys like this:
for k, v in sorted(somedictionary.iteritems()):
doSomething(k, v)
Answered by: John391 | Posted: 01-03-2022
Answer 2
Can I answer my own question?
I have just discovered the handy function "sorted" which does exactly what I was looking for.
for k in sorted(somedictionary.keys()): dosomething()
It shows up in Python 2.5 dictionary 2 key sort
Answered by: Brad660 | Posted: 01-03-2022Answer 3
Actually, .keys() is not necessary:
for k in sorted(somedictionary):
doSomething(k)
or
[doSomethinc(k) for k in sorted(somedict)]
Answered by: Gianna398 | Posted: 01-03-2022
Similar questions
python - better one-liner to flip keys and values of a dictionary
I've written a one-liner to accomplish this:
vocab_tag = dict(zip(*reversed(zip(*tag_vocab.items()))))
Can anybody write one that's more comprehensible/direct?
python - Create a dictionary from two lists in a one-liner
From these lists,
lst1 = ['a','b','c']
lst2 = [[1,2],[3,4,5],[6,7]]
I want to create:
{1: 'a', 3: 'b', 6: 'c', 2: 'a', 4: 'b', 7: 'c', 5: 'b'}
I can create it using a for loop:
d = {}
for l, nums in zip(lst1, lst2):
for num in nums:
d[num] = l
I figured I need to use map and zip, so I tried,
dict(map(l...
python - better one-liner to flip keys and values of a dictionary
I've written a one-liner to accomplish this:
vocab_tag = dict(zip(*reversed(zip(*tag_vocab.items()))))
Can anybody write one that's more comprehensible/direct?
python - Is there a one-liner to put a string in a list an amount of times that's specified in a dictionary?
I have a dictionary that contains string, integer pairs like this:
dict = {
'a': 2,
'b': 0,
'c': 3
}
I need to generate the following list from it:
list = ['a', 'a', 'c', 'c', 'c']
Now, I can do this with a normal function quite easily:
python - Create a dictionary from two lists in a one-liner
From these lists,
lst1 = ['a','b','c']
lst2 = [[1,2],[3,4,5],[6,7]]
I want to create:
{1: 'a', 3: 'b', 6: 'c', 2: 'a', 4: 'b', 7: 'c', 5: 'b'}
I can create it using a for loop:
d = {}
for l, nums in zip(lst1, lst2):
for num in nums:
d[num] = l
I figured I need to use map and zip, so I tried,
dict(map(l...
sorting - 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'}
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 - 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