How to merge values of two arrays into one? [duplicate] - python

This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
Closed 1 year ago.
How to merge two arrays as value-pairs in python?
Example as follows:
A = [0,2,2,3]
B = [1,1,4,4]
Output:
[[0,1],[2,1],[2,4],[3,4]]

You can simply use "zip"
l1 = [0,2,2,3]
l2 = [1,1,4,4]
print(list(map(list ,zip(l1,l2))))

In addition to Greg's answer, if you need key value pairs cast your zip result to dict
l1 = [0,2,2,3]
l2 = [1,1,4,4]
print(dict(zip(l1,l2)))
Output
{0: 1, 2: 4, 3: 4}
Before creating any loop, try to use built-ins.
Also there is a similar question for your need
Zip with list output instead of tuple

You can simultaniously itterate through using zip(), and append a result list with each of the pairs like so:
A = [0,2,2,3]
B = [1,1,4,4]
result = []
for item1, item2 in zip(A,B):
result.append([item1, item2])
Output = [[0,1],[2,1],[2,4],[3,4]]
print(result) # Prints: [[0,1],[2,1],[2,4],[3,4]]
print(Output == result) # Prints: True
This would give you a list of lists like you were looking for in your question as an output.
Things to keep in mind
If the two starting lists are different sizes then zip() throws away values after one of the lists runs out, so with :
A = [0,2,2,3,4,5]
B = [1,1,4,4]
result = []
for item1, item2 in zip(A,B):
result.append([item1, item2])
Output = [[0,1],[2,1],[2,4],[3,4]]
print(result) # Prints: [[0,1],[2,1],[2,4],[3,4]]
print(Output == result) # Prints: True
You notice that the 4 and 5 in list A is thrown out and ignored.
Key-Value Pair
Also this is not a key-value pair, for that you will want to look into dictionaries in python. That would be something like:
output = {0:1, 2:4, 3:4}
This would allow you to do a lookup for a value, based on it's key like so:
output[3] # Would be 4
output[0] # Would be 1
Which doesn't work for this example because there are two 2's used as keys, so one would be overridden.

Since you have mentioned key-value, you probably mean a dictionary.
A = [0, 2, 2, 3]
B = [1, 1, 4, 4]
dct = {} # Empty dictionary
for key, value in zip(A, B):
dct[key] = value
print(dct)
The output will be:
{0: 1, 2: 4, 3: 4}
Note that, by definition, you can't have two identical keys. So in your case, {2: 1} will be overriden by {2: 4}.

Related

Can't crate a dictionary from two lists using dictionary comprehension with two FORs. Why?

I know that there are a bunch of ways to make a dictionary out of two lists, but I wanted to do it using two FOR loops to iterate over both lists. Therefore, I used the following code. Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys and only considers the last element of the list as the value.
key = ['hello', 'mello', 'vello']
value = [1, 2, 3]
dictionary = {k: v for k in key for v in value}
print('dictionary is ', dictionary)
the result was:
dictionary is: {'hello': 3, 'mello': 3, 'vello': 3}
But I expect that the result would be:
dictionary is: {'hello': 1, 'mello': 2, 'vello': 3}
I appreciate it if anyone can clarify this for me.
My understanding is the full dictionary is being recreated each loop with each number as the key, resulting in only your final output being that of the last value (best shown by reversing your key and value statements, returning {1: 'vello', 2: 'vello', 3: 'vello', 4: 'vello'}
If the other is your intended output, this should work fine:
dictionary = dict(zip(key,value))
You can use zip for this purpose.
dictionary = dict(zip(keys, values))

Create a key:value pair in the first loop and append more values in subsequent loops

How can I create a key:value pair in a first loop and then just append values in subsequent loops?
For example:
a = [1,2,3]
b = [8,9,10]
c = [4,6,5]
myList= [a,b,c]
positions= ['first_position', 'second_position', 'third_position']
I would like to create a dictionary which records the position values for each letter so:
mydict = {'first_position':[1,8,4], 'second_position':[2,9,6], 'third_position':[3,10,5]}
Imagine that instead of 3 letters with 3 values each, I had millions. How could I loop through each letter and:
In the first loop create the key:value pair 'first_position':[1]
In subsequent loops append values to the corresponding key: 'first_position':[1,8,4]
Thanks!
Try this code:
mydict = {}
for i in range(len(positions)):
mydict[positions[i]] = [each[i] for each in myList]
Output:
{'first_position': [1, 8, 4],
'second_position': [2, 9, 6],
'third_position': [3, 10, 5]}
dictionary.get('key') will return None if the key doesn't exist. So, you can check if the value is None and then append it if it isn't.
dict = {}
for list in myList:
for position, val in enumerate(list):
this_position = positions[position]
if dict.get(this_position) is not None:
dict[this_position].append(val)
else:
dict[this_position] = [val]
The zip function will iterate the i'th values of positions, a, b and c in order. So,
a = [1,2,3]
b = [8,9,10]
c = [4,6,5]
positions= ['first_position', 'second_position', 'third_position']
sources = [positions, a, b, c]
mydict = {vals[0]:vals[1:] for vals in zip(*sources)}
print(mydict)
This created tuples which is usually fine if the lists are read only. Otherwise do
mydict = {vals[0]:list(vals[1:]) for vals in zip(*sources)}

How to split a dictionary of lists with arbitrary number of values into a list of dictionaries?

I am trying to split a dictionary of lists into a list of dictionaries.
I have tried following the examples here and here_2. Here_2 is for python 2.x and does not seem to work on python 3.x
The first linked example, here, almost works except I only get the first dictionary key value pair back as 1 list.
using zip() to convert dictionary of list to list of dictionaries
test_dict = { "Rash" : [1], "Manjeet" : [1], "Akash" : [3, 4] }
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())]
print ("The converted list of dictionaries " + str(res))
Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}]
DESIRED Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}, {‘Akash’: 4}]
Here's a slow and brittle solution with no bells or whistles (and bad naming in general):
def dictlist_to_listdict(dictlist):
output = []
for k, v in dictlist.items():
for i, sv in enumerate(v):
if i >= len(output):
output.append({k: sv})
else:
output[i].update({k: sv})
return output
if __name__ == "__main__":
test_dict = {"Rash": [1], "Manjeet": [1], "Akash": [3, 4]}
print(dictlist_to_listdict(test_dict))
When I ran your code on my notebook with Python 3, it does print the line you put as the desired output. Perharps I don't understand the question well enough

How to append a dictionary to key in another dictionary?

So I want my end output to look like this:
answer = {'A':{1,2,3,4},'B':{1,2,3,4}}
How can I do this? I have a few questions though.
How do I make a dictionary without a key pair value. Like {1,2,3,4}
How do I append the {1,2,3,4} to a key ('A').
How do I append the A into the main dictionary(answer)
Essentially I am trying to make this bit in a loop 'A':{1,2,3,4}. Then outside the loop append it to answer.
{1,2,3,4} is a set, not a dict.
You can add the A key and its value (the set) like so:
answer = {}
answer["A"] = {1,2,3,4}
If you have a set, you can add:
>>> s = {1,2}
>>> s
{1, 2}
>>> s.add(3)
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
To iterate:
>>> for item in answer['A']:
... print(item)
...
1
2
3
4
If you want to build a dictionary like that given a list of keys and a set you can do:
list_of_keys = ["A", "B", "C"]
some_set = {1,2,3,4}
my_dict = {key: some_set for key in list_of_keys}
Is there a specific reason why you want to use dictionary and append values into it?
You can use a dictionaries of list:
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = []
# Inner Loop
answer[i].append(j) # j = 1, 2, 3, 4
print(answer) # {'A':[1,2,2,3,4],'B':[1,1,2,3,4]}
If you do not want duplicates then you can use a set instead of a list.
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = set()
# Inner Loop
answer[i].add(j) # j = 1, 2, 3, 4
print(answer) # {'A':(1,2,3,4),'B':(1,2,3,4)}
Hope this helps, Cheers!

Combine 2 dictionaries by key-value in python

I have not found a solution to my question, yet I hope it's trivial.
I have two dictionaries:
dictA:
contains the order number of a word in a text as key: word as value
e.g.
{0:'Roses',1:'are',2:'red'...12:'blue'}
dictB:
contains counts of those words in the text
e.g.
{'Roses':2,'are':4,'blue':1}
I want to replace the values in dictA by values in dictB via keys in dictB, checking for nones, replacing by 0.
So output should look like:
{0:2,1:4,2:0...12:1}
Is there a way for doing it, preferentially without introducing own functions?
Use a dictionary comprehension and apply the get method of dict B to return 0 for items that are not found in B:
>>> A = {0:'Roses',1:'are',2:'red', 12:'blue'}
>>> B = {'Roses':2,'are':4,'blue':1}
>>> {k: B.get(v, 0) for k, v in A.items()}
{0: 2, 1: 4, 2: 0, 12: 1}

Categories

Resources