This question already has answers here:
How to keep keys/values in same order as declared?
(13 answers)
Closed 6 years ago.
I am trying to add elements to a dictionary in the following way:
a = {}
a['b'] = 1
a['a'] = 2
Finally a looks like:
{'a': 2, 'b': 1}
But actually I wanted the dictionary to contain keys in the order:
{'b': 1, 'a': 2}
Can anyone explain me this? Why are the keys getting sorted alphabetically when actually dictionaries (hashmaps) don't have any order?
You are correct in that dictionaries are not ordered, but hashed. As a result, the order of a dictionary should not be relied on.
You can use the OrderedDict to help you achieve your goal:
from collections import OrderedDict
a = OrderedDict()
a['b'] = 1
a['a'] = 2
> a
> OrderedDict([('b', 1), ('a', 2)])
Related
This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
How do I merge dictionaries together in Python?
(7 answers)
Closed 1 year ago.
I have a large list of dictionaries, each with exactly one entry and with unique keys, and I want to 'combine' them into a single dict with python 3.8.
So here is an example that actually works:
mylist = [{'a':1}, {'b':2}, {'c':3}]
mydict = {list(x.keys())[0]:list(x.values())[0] for x in mylist}
which gives as result the expected output:
{'a': 1, 'b': 2, 'c': 3}
But it looks ugly and not quite pythonic. Is there a better one-line solution to this problem?
This is similar to the question asked HERE, but in my example I am looking for an answer (1) to merge many dicts together and (2) for a one-line solution. That makes my question different from the question already asked.
mydict = { k:v for elt in mylist for k, v in elt.items()}
Try this out, simple and effective.
mylist = [{'a':1}, {'b':2}, {'c':3}]
result = {}
for d in mylist:
result.update(d)
Result
{'a': 1, 'b': 2, 'c': 3}
This question already has answers here:
Is it possible to assign the same value to multiple keys in a dict object at once?
(8 answers)
Closed 3 years ago.
Is there a compact way to have alternative keys for the same value in a dictionary?
Taking a dictionary like the following
dict={'A':1,'B':2,'one':1,'two':2}
I can obtain the value 1 using two different keys:
dict['A']
dict['one']
I would like to know if there is a more compact way to write it, something akin to:
dict2={['A','one']:1,['B','two']:2}
You can define the dict with keys of the same value grouped as a tuple first:
d = {('A', 'one'): 1, ('B', 'two'): 2}
so that you can then convert it to the desired dict with:
d = {key: value for keys, value in d.items() for key in keys}
d becomes:
{'A': 1, 'one': 1, 'B': 2, 'two': 2}
This question already has answers here:
In an OrderedDict how to sort by a particular attribute? [closed]
(1 answer)
How do I sort a dictionary by key?
(32 answers)
Closed 4 years ago.
Heres what I have:
dict = {'b':[456], 'a': [123]}
sort_dict = sorted(dict.items(), key = str)
return sort_dict
What my code returns:
[('a', [123]), ('b', [456])]
what I need it to return:
{'a':[123], 'b':[456]}
I know I can make a for loop or something to make a new dict, but is there another/simpler way to do this? Thanks!
from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=str))
OrderedDict([('a', [123]), ('b', [456])])
For Python 3.6+ this is enough (read comments for more details):
d = {'b':[456], 'a': [123]}
>>> dict(sorted(d.items(), key=str))
{'a': [123], 'b': [456]}
Don't name your variables dict, list, str, etc. as these are the names of the built-in functions.
This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 6 years ago.
In python, I have a dictionary named dict_a :
dict_a = {'a':1}
and I want to get a new dictionary dict_b as the update of dict_a,at the same time I don't want to change the dict_a, so I used this:
dict_b = copy.deepcopy(dict_a).update({'b':2})
However, the return value of dict.update is None, so the above code doesn't work. And I have to use this:
temp = copy.deepcopy(dict_a)
temp.update({'b':2})
dict_b = temp
The question is, how to get my goal in one line? Or some
What about:
>>> a = {'a':1}
>>> update = {'b': 1}
>>> b = dict(a.items() + update.items())
>>> b
{'a': 1, 'b': 1}
update - is your value that need to update(extend) dict a
b - is a new resulting dict
Anfd in this case a stay unchanged
This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Xpath like query for nested python dictionaries
(11 answers)
Closed 6 years ago.
Is there a recursive itemgetter in python. Let's say you have an object like
d = {'a': (1,2,3), 'b': {1: (5,6)}}
and I wanted to get the first element of the tuple from d['a']? As far as I can tell itemgetter will only do one level, i.e. get me a or b or both.
Is there some clever way of combining itertools with itemgetter to produce the desired result.
So basically what I want to be able to call is
from operator import itemgetter
d = {'a': (1,2), 'b': (4, (5,))}
itemgetter({'a': 0})(d) --> 1
itemgetter({'b': 0})(d) --> 4
itemgetter({'b': {1: 0}})(d) --> 5
d = {'a': {'b': (1,2,3)}}
itemgetter({'a': {'b': 2}})(d) --> 3
I don't like 'clever' ways. Obvious is better.
You can very easily write a getter that iterates along a list of subscripts:
def getter(x, *args):
for k in args:
x = x[k]
return x
>>> d = {'a': (1,2,3), 'b': {1: (5,6)}}
>>> getter(d, 'a', 0)
1