Python - Converting list to dict pairwise [duplicate] - python

This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 4 years ago.
I have a list that looks like this:
mylist = [1, 'a', 2, 'b', 3, 'c']
and would like to end up with a dictionary:
mydict = {
'a': 1,
'b': 2,
'c': 3,}
At the moment I'm achieving it like so:
mydict = {}
for i, k in enumerate(mylist):
if i == len(mylist)/2:
break
v = 2 * i
mydict[mylist[v+1]] = mylist[v]
Is there a more pythonic way of achieving the same thing? I looked up the itertools reference but didn't find anything in particular that would help with the above.
Note: I'm happy with what I have in terms of achieving the goal, but am curious if there is anything that would be more commonly used in such a situation.

Try this
# keys
k = mylist[1::2]
# values
v = mylist[::2]
# dictionary
mydict = dict(zip(k, v))

Related

Python custom sorting [duplicate]

This question already has answers here:
Sort a list with a custom order in Python
(4 answers)
Closed 2 months ago.
I have a list of objects like this:
my_list = [obj1,obj2,obj3, ...]
Each object has some data like:
obj = {
'id':1,
'name':'Some name',
'value': 'Some value',
'category':'A'
}
The category options are: CATEGORY = {'A','B','C','D'}
Is it possible to sort the list somehow to display data in sequence like:
my_sordet_list = ['all in C categ', 'all in B categ', 'all in D categ','all in A categ']
So the question is: How can I explain to the program that I want it to be sorted in a strict custom sequence?
You could create a lookup dictionary for your custom ordering:
>>> category_order = {'C': 0, 'B': 1, 'D': 2, 'A': 3}
>>> my_sorted_list = sorted(mylist, key=lambda o: category_order[o['category']])
my_sorted_list will be sorted, as you desire.

In python, is it possible to assign one of multiple variables with the same prefix to another variable dynamically? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
The question is about to getting one of multiple data in a run time. There are several data such as
dict_a = {'shape':1}
dict_b = {'opt':'sp'}
dict_c = ...
From the function with job of 'a', 'b', 'c', etc. Rather than using just long repetitive coding such as
if job == 'a':
dic = dict_a
elif job == 'b':
dic = dict_b
...
I want to write a more smart coding. I have tried this with exec, but this does not work.
def running(job):
dictname = 'dict_'+job
var = 'dic'
exec("%s = %s" % (var, dictname))
if "dic" in locals():
print(f"True, {dic}")
"dic" seems to be made by exec() but cannot use dic. The error message goes as follows:
print(f"True, {dic}")
NameError: name 'dic' is not defined
dictionary of dictionaries is more efficient but another possible solution to this is the use of eval
>>> dict_a = {'shape':1}
>>> dict_b = {'opt':'sp'}
>>> job = "dict_a"
>>> dic = eval(job)
>>> dic
{'shape': 1}
Using a dictionary of dictionaries would be much easier:
mega_dict = {'a': {'shape':1}, 'b' :{'opt':'sp'}}
print(mega_dict['a']['shape']) # or any other usage...
You can create a dictionary consisting of all dictionaries. Something like this
final_dict = {'dict_a' : dict_a, 'dict_b' : dict_b}
Then in your running method, you can just simply do
dictname = 'dict_' + job
dic = final_dict[dictname]

How to create a list of dicts into a single dict with python? [duplicate]

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}

Python: How to get the updated dictionary in 1 line? [duplicate]

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

Appending new key to a dictionary [duplicate]

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

Categories

Resources