Python merge two lists with different lengths - python-2.7

Hi please help me develop a logic which does following.
list_1 = [1,2,3]
list_2 = [a,b,c,d,e,f,g,h,i]
Required output (List of dictionaries):
output = [{1:a,2:b,3:c}, {1:d,2:e,3:f}, {1:g,2:h,3:i}]
My script:
return_list = []
k = 0
temp_dict = {}
for i, value in enumerate(list_2):
if k <= len(list_1)-1:
temp_dict[list_1[k]] = value
if k == len(list_1)-1:
k = 0
print temp_dict
return_list.append(temp_dict)
print return_list
print '\n'
else:
k = k + 1
print return_list
My output:
{1: 'a', 2: 'b', 3: 'c'}
[{1: 'a', 2: 'b', 3: 'c'}]
{1: 'd', 2: 'e', 3: 'f'}
[{1: 'd', 2: 'e', 3: 'f'}, {1: 'd', 2: 'e', 3: 'f'}]
{1: 'g', 2: 'h', 3: 'i'}
[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]
[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]
As you can see, temp_dict is getting printed correctly, but return_list is the last temp_dict 3 times.
please help to solve.

return_list = []
k = 0
temp_dict = {}
for i, value in enumerate(list_2):
if k <= len(list_1)-1:
temp_dict[list_1[k]] = value
if k == len(list_1)-1:
k = 0
print temp_dict
return_list.append(temp_dict)
temp_dict = {}
else:
k = k + 1

For simple, you could use zip
list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']
chunks = [list_2[idx:idx+3] for idx in range(0, len(list_2), 3)]
output = []
for each in chunks:
output.append(dict(zip(list_1, each)))
print(output)

from itertools import cycle
list_1 = [1, 2, 3]
list_2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
zipped = tuple(zip(cycle(list_1), list_2))
out = list(map(dict, chunks(zipped, len(list_1))))
print(out)
Gives you:
[{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]

Related

Merging to lists of different length to for list of dictionaries

Hi please help me develop a logic which does following.
list_1 = [1,2,3]
list_2 = [a,b,c,d,e,f,g,h,i]
Required output (List of dictionaries):
output = [{1:a,2:b,3:c}, {1:d,2:e,3:f}, {1:g,2:h,3:i}]
My script:
return_list = []
k = 0
temp_dict = {}
for i, value in enumerate(list_2):
if k <= len(list_1)-1:
temp_dict[list_1[k]] = value
if k == len(list_1)-1:
k = 0
print temp_dict
return_list.append(temp_dict)
print return_list
print '\n'
else:
k = k + 1
print return_list
My output:
{1: 'a', 2: 'b', 3: 'c'}
[{1: 'a', 2: 'b', 3: 'c'}]
{1: 'd', 2: 'e', 3: 'f'}
[{1: 'd', 2: 'e', 3: 'f'}, {1: 'd', 2: 'e', 3: 'f'}]
{1: 'g', 2: 'h', 3: 'i'}
[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]
[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]
As you can see, temp_dict is getting printed correctly, but return_list is the last temp_dict 3 times.
please help to solve.
The issue here is that you are not reseting temp_dict to a new object.
When you append it to the list, it still maintains the reference to the dict object, after you change it on the next loop, it changes the value on the array because it's the same reference.
If you reset the value it should work
list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']
return_list = []
k = 0
temp_dict = {}
for i, value in enumerate(list_2):
if k <= len(list_1)-1:
temp_dict[list_1[k]] = value
if k == len(list_1)-1:
k = 0
print temp_dict
return_list.append(temp_dict)
temp_dict = {} # Here is the change
print return_list
print '\n'
else:
k = k + 1
print return_list
This should work:
list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']
output = []
j = 0
for i in range(1, len(list_1) + 1):
output.append(dict(zip(list_1, list_2[j:i * 3])))
j = i * 3
print(output)
The assumption is that you second list is exactly 3 times larger than the first list.
def merge_them(list1, list2):
output = []
i = 0
while i < len(list_2):
output.append(dict(zip(list_1, list_2[i: i + len(list1)])))
i += len(list1)
return output
and you can test it:
test1:
list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']
print merge_them(list_1, list_2)
you will get:
[{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]
test2:
list_1 = [1,2,3,]
list_2 = ['a','b','c','d','e']
print merge_them(list_1, list_2)
you will get:
[{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e'}]
test3:
list_1 = [1,2,3,4,5,6,7,8]
list_2 = ['a','b','c','d','e']
print merge_them(list_1, list_2)
you will get:
[{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}]

Fetching values from one dictionary and putting their product into other dictionary

I have these two such dictionaries:
dict1={'C': '0.01464117821', 'E': '0.0621048942', 'D': '0.05465751502', 'G': '0.06693173594', 'F': '0.03875843054', 'I': '0.05478210779', , 'K': '0.05233761138', 'M': '0.02187736464', 'L': '0.09578482304', 'N': '0.04211449136', , 'P': '0.05051274639', 'T': '0.0573250668', , 'V': '0.06446141032', 'Y': '0.02954265733'}
dict2={'CVCVCVCV': ['C', 'V', 'C', 'V', 'C', 'V', 'C', 'V'], 'FEPFFTTK': ['F', 'E', 'P', 'F', 'F', 'T', 'T', 'K'],]}
I want a result like:
dict3={'CVCVCVCV': [value of C from dict1*value of V from dict1..and so on], 'FEPFFTTK': [value of F from dict1*value of E from dict1* value of P from dict1... and so on],]}
def product(x):
a = 1
for i in x:
a *= i
return a
dict1={'A': '0.08449754996', 'C': '0.01464117821', 'E': '0.0621048942', 'D': '0.05465751502', 'G': '0.06693173594', 'F': '0.03875843054', 'I': '0.05478210779', 'H': '0.02252015864', 'K': '0.05233761138', 'M': '0.02187736464', 'L': '0.09578482304', 'N': '0.04211449136', 'Q': '0.040185413', 'P': '0.05051274639', 'S': '0.07603976756', 'R': '0.05819425977', 'T': '0.0573250668', 'W': '0.01273081812', 'V': '0.06446141032', 'Y': '0.02954265733'}
dict2={'CVCVCVCV': ['C', 'V', 'C', 'V', 'C', 'V', 'C', 'V'], 'FEPFFTTK': ['F', 'E', 'P', 'F', 'F', 'T', 'T', 'K'], 'SHELRTPL': ['S', 'H', 'E', 'L', 'R', 'T', 'P', 'L'], 'DFGTGYS': ['D', 'F', 'G', 'T', 'G', 'Y', 'S'], 'QTNLLALN': ['Q', 'T', 'N', 'L', 'L', 'A', 'L', 'N'], 'PNGAGKTT': ['P', 'N', 'G', 'A', 'G', 'K', 'T', 'T']}
for key, values in dict2.items():
for i in range(len(values)):
values[i] = float(dict1[values[i]])
dict3 = {}
for key, values in dict2.items():
dict3[key] = product(values)
from __future__ import division
import numpy as np
dict1={'A': '0.08449754996', 'C': '0.01464117821', 'E': '0.0621048942', 'D': '0.05465751502', 'G': '0.06693173594', 'F': '0.03875843054', 'I': '0.05478210779', 'H': '0.02252015864', 'K': '0.05233761138', 'M': '0.02187736464', 'L': '0.09578482304', 'N': '0.04211449136', 'Q': '0.040185413', 'P': '0.05051274639', 'S': '0.07603976756', 'R': '0.05819425977', 'T': '0.0573250668', 'W': '0.01273081812', 'V': '0.06446141032', 'Y': '0.02954265733'}
dict2={'CVCVCVCV': ['C', 'V', 'C', 'V', 'C', 'V', 'C', 'V'], 'FEPFFTTK': ['F', 'E', 'P', 'F', 'F', 'T', 'T', 'K'], 'SHELRTPL': ['S', 'H', 'E', 'L', 'R', 'T', 'P', 'L'], 'DFGTGYS': ['D', 'F', 'G', 'T', 'G', 'Y', 'S'], 'QTNLLALN': ['Q', 'T', 'N', 'L', 'L', 'A', 'L', 'N'], 'PNGAGKTT': ['P', 'N', 'G', 'A', 'G', 'K', 'T', 'T']}
for key, values in dict2.items():
for i in range(len(values)):
values[i] = float(dict1[values[i]])
dict3 = {}
for key, values in dict2.items():
dict3[key] = np.product(values)

Counter in Python

Is there a way to collect values in Counter with respect to occurring number?
Example:
Let's say I have a list:
list = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd']
When I do the Counter:
Counterlist = Counter(list)
I'll get:
Counter({'b': 3, 'a': 3, 'c': 3, 'd': 2})
Then I can select let's say a and get 3:
Counterlist['a'] = 3
But how I can select the occurring number '3'?
Something like:
Counterlist[3] = ['b', 'a', 'c']
Is that possible?
You can write the following
import collections
my_data = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd']
result = collections.defaultdict(list)
for k, v in collections.Counter(my_data).items():
result[v].append(k)
and then access result[3] to obtain the characters with that count.

Python: out of range list for random creation of alphabet

I want to create a random alphabet. So my code is the following:
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def new_alphabet():
for i in range(0, 26):
j = 25
my_new_alphabet = [None] * 26
my_new_alphabet[i] = alphabet[random.randint(0, j)]
alphabet.remove(my_new_alphabet[i])
j = j-1
return my_new_alphabet
print new_alphabet()
But when I try to execute it:
my_new_alphabet[i] = alphabet[random.randint(0, j)]
IndexError: list index out of range
It is probably something fairly simple but I cannot manage to find where the problem is. Thanks in advance.
There are some problems with your code.
your alphabet is missing the letter "S", so it has only 25 elements, thus the ranges for your loop and for your random indices are one-off, thus the out-of-range error
the lines j = 25 and my_new_alphabet = [None] * 26 should go before the loop, otherwise you are resetting them in each iteration
Also, you could drop j entirely and just use the bounds of the actual alphabet list instead:
def new_alphabet():
my_new_alphabet = []
while alphabet:
letter = alphabet[random.randint(0, len(alphabet) - 1)]:
# or just use this: letter = random.choice(alphabet)
alphabet.remove(letter)
my_new_alphabet.append(letter)
return my_new_alphabet
Or just use random.shuffle, which does exactly what you want:
def new_alphabet():
my_new_alphabet = list(alphabet) # copy
random.shuffle(my_new_alphabet)
return my_new_alphabet

Combinations of strings from data

So, we have data. a little big data.
example.
0 -> [a, b]
1 -> c
2 -> [d, e, f]
3 -> [g, h]
4 -> k
5 -> l
we need to combine each of this values. for this example output will be a lot of variants.
acdgkl
acdhkl
acegkl
acehkl
acfgkl
acfhkl
bcdgkl
bcdhkl
bcegkl
bcehkl
bcfgkl
bcfhkl
Quetion: what is this action procedure of combinating values called?)
and how to realize it :)
THX.
The process which turns something like
[['a','b'], ['c'], ['d', 'e', 'f'], ['g', 'h'], ['k'], ['l']]
into the sequence
[['a','c','d','g','k','l'],
['a','c','d','h','k','l'],
...
is called taking the Cartesian product. I don't think there's a name for the specific process of also concatenating the result when they're strings. (Also note that I've made each term a list, even if it's a list of one element, rather than alternating between lists (['a','b']) and scalars ('c')).
This is a common enough process that many languages have built-in support, e.g. Python:
>>> from itertools import product
>>> source = [['a','b'], ['c'], ['d', 'e', 'f'], ['g', 'h'], ['k'], ['l']]
>>> outputs = product(*source)
>>> for out in outputs:
... print(out)
...
('a', 'c', 'd', 'g', 'k', 'l')
('a', 'c', 'd', 'h', 'k', 'l')
('a', 'c', 'e', 'g', 'k', 'l')
('a', 'c', 'e', 'h', 'k', 'l')
('a', 'c', 'f', 'g', 'k', 'l')
('a', 'c', 'f', 'h', 'k', 'l')
('b', 'c', 'd', 'g', 'k', 'l')
('b', 'c', 'd', 'h', 'k', 'l')
('b', 'c', 'e', 'g', 'k', 'l')
('b', 'c', 'e', 'h', 'k', 'l')
('b', 'c', 'f', 'g', 'k', 'l')
('b', 'c', 'f', 'h', 'k', 'l')
Even if the language you're using doesn't support this natively, it's straightforward to implement.
Believe you are looking for Permutation and Combination.
Try using nested loops.
I can't comment on the comment of DSM (as I don't have enough points)
But if you want to concatenate the lists and print them as strings use
print ''.join(out)
instead of
print