This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 2 years ago.
I have:
a = {'name':'alfred','class':'2'}
b = {'year':'1990','town':'NY'}
And I want to merge a and b to get:
{'name':'alfred','class':'2', 'year':'1990','town':'NY'}
So far I created a new dict and iterate through both to set key values pairs.
Python3.9
c = a | b
Python3.5+
c = {**a, **b}
Related
This question already has answers here:
Repeating list in python N times? [duplicate]
(4 answers)
Closed 12 months ago.
suppose I have a list
a = [1,2,4,5]
I want to create another list b which clones a and adds it 3 times. So b is expected to be
b = [1,2,4,5,1,2,4,5,1,2,4,5]
How do I do this easily?
Methods using pandas or numpy is also welcome.
#just use the * operator
b=a*3
This question already has answers here:
Pythonic way to create union of all values contained in multiple lists
(7 answers)
How to get the union of two lists using list comprehension? [duplicate]
(2 answers)
Closed 2 years ago.
Given two list A and B, It the following the way to put all elements in teo set together avoiding repetitions?
[i for i in A \if i not in B]
This question already has answers here:
Accessing elements of Python dictionary by index
(11 answers)
Closed 3 years ago.
I created a dictionary with key with multiple values. How can I access those values from single key?
d = {'a':(1,2,3),('b','c'):5}
I want to access the values 1,2 or 3 using the key 'a'.
d['a'] is a tuple, and like any tuple you can access it's elements as such: d['a'][0] which holds the value 1
This question already has an answer here:
How to index into nested lists?
(1 answer)
Closed 4 years ago.
I have a list containing tupels, i.e.
df = [('apa', 'apc'), ('apa', 'bp'), ('br', 'bpt')]
with
df[0]
I would get
('apa', 'apc')
How could I get 'apa' only from that tuple?
I believe you are looking for this:
a, b = df[0]
which in case of your data would set value of a to apa and b to apc. If you want just to get apa from your tuple, then refer as you'd with lists:
a = df[0][0]
This question already has answers here:
How do I combine two lists into a dictionary in Python? [duplicate]
(6 answers)
Closed 7 years ago.
Is there any build-in function in Python that merges two lists into a dict? Like:
combined_dict = {}
keys = ["key1","key2","key3"]
values = ["val1","val2","val3"]
for k,v in zip(keys,values):
combined_dict[k] = v
Where:
keys acts as the list that contains the keys.
values acts as the list that contains the values
There is a function called array_combine that achieves this effect.
Seems like this should work, though I guess it's not one single function:
dict(zip(["key1","key2","key3"], ["val1","val2","val3"]))
from here: How do I combine two lists into a dictionary in Python?