I have two lists:
list1 = [IM12345, IM12346, IM12347, IM12348]
list2 = [ID300, ID404, ID300, ID601]
list2 associates with the corresponding list1 values. list1 has unique values where as list2 has duplicates.
I want to make list2 unique corresponding associated value will add in the that list2 value.
Dict= {ID300: {IM12345, IM12347}, ID404: IM12346, ID601: IM12348}
Above pattern can be in list, set or dictionary.
Which algorithm in python should I use to get the above result?
You could try collections.defaultdict:
from collections import defaultdict
d = defaultdict(set)
list1 = ['IM12345', 'IM12346', 'IM12347', 'IM12348']
list2 = ['ID300', 'ID404', 'ID300', 'ID601']
for key, value in zip(list2, list1):
d[key].add(value)
Demo:
>>> d
defaultdict(<class 'set'>, {'ID300': {'IM12345', 'IM12347'}, 'ID404': {'IM12346'}, 'ID601': {'IM12348'}})
>>>
>>>
>>> for i, j in d.items():
... print(i, j)
...
...
ID601 {'IM12348'}
ID300 {'IM12345', 'IM12347'}
ID404 {'IM12346'}
You can create a dict to save the dataset
list1 = ["IM12345", "IM12346", "IM12347", "IM12348"]
list2 = ["ID300", "ID404", "ID300", "ID601"]
dictResult=dict()
i=0
for item in list2:
print item
if dictResult.has_key(item):
dictResult[item].append(list1[i])
else:
dictResult[item]=[list1[i]]
i=i+1
print dictResult
Result:
{'ID404': ['IM12346'], 'ID300': ['IM12345', 'IM12347'], 'ID601': ['IM12348']}
Might not completely be a pythonic way but - here it goes:
Map the input:
map = dict(zip(list1, list2))
Now you can do an inverse mapping:
inv_map = {}
for k, v in map.iteritems():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
Result for the example above:
>>> inv_map
{'ID404': ['IM12346'], 'ID300': ['IM12345', 'IM12347'], 'ID601': ['IM12348']}
Another way of doing it could be with list operations.
yourList = ["1","2","3","4","1","2"]
newList = []
for f in yourList:
if f not in newList:
newList.append(f)
Simple solution
from collections import defaultdict
list1 = ['IM12345', 'IM12346', 'IM12347', 'IM12348']
list2 = ['ID300', 'ID404', 'ID300', 'ID601']
d = defaultdict(list)
for n in range(len(list2)):
d[list2[n]].append(list1[n])
print d.items()
Result:
[('ID404', ['IM12346']), ('ID300', ['IM12345', 'IM12347']), ('ID601', ['IM12348'])]
Python2.7 Documentation----defaultdict
Related
I have the following list:
[('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]
I want to create the following dictionary with Key value pair from the list as:
{'0-N':['3-C'],'3-C':['0-N','5-C','9-C'],'9-C':['3-C','12-C'],'12-C':['9-C']}
Any suggestions or help will be highly appreciated.
Use collections.defaultdict:
from collections import defaultdict
lst = [('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]
dct = defaultdict(list)
for tup in lst:
dct[tup[0]].append(tup[1])
dct[tup[1]].append(tup[0])
dct = dict(dct)
print(dct)
{'0-N': ['3-C'], '3-C': ['0-N', '5-C', '9-C'], '5-C': ['3-C'], '9-C': ['3-C', '12-C'], '12-C': ['9-C']}
You may use built-in function dict.setdefault:
lst = [('0-N', '3-C'), ('3-C', '5-C'), ('3-C', '9-C'), ('9-C', '12-C')]
dct = {}
for a, b in lst:
dct.setdefault(a, []).append(b)
dct.setdefault(b, []).append(a)
I have two lists like this:
list1[(0,123),(1,456)]
list2[(0,'asd'),(2,'dsa'),(0,'eqw')]
I want merge above two lists into one where the first element in both lists is matched, for example, 0 in list1 can be found in list2, the output should like
list3[(0,123,'asd','eqw')]
I tried this code, but seems not work:
out = [i for i,j in zip(list1, list2) if list1[0][0] == list[0][0]]
Can someone give me any solution? Thanks!
You could use a collections.defaultdict for this:
>>> from collections import defaultdict
>>> list1 = [(0,123),(1,456)]
>>> list2 = [(0,'asd'),(2,'dsa'),(0,'eqw')]
>>> d = defaultdict(list)
>>> for k,v in list1+list2:
... d[k].append(v)
...
>>> d
defaultdict(<class 'list'>, {0: [123, 'asd', 'eqw'], 1: [456], 2: ['dsa']})
>>> d1, d2 = dict(list1), dict(list2)
>>> [(k,v) for k,v in d.items() if k in d1 and k in d2]
[(0, [123, 'asd', 'eqw'])]
I have the following Python list:
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
I would like to take the entries of this list and create a dictionary of key-values pairs that looks like
dictionary_list1 = {'EW':'G:B<<LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A<F<AF', 'GR':'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX':'F:-111', 'DS':'f:115.5', 'MW':'AA:0', 'MA':'A:0XT:i:0', 'EW':'EE:KJERWEWERKJWE'}
How does one parse/split the list above list1 to do this? My first instinct was to try try1 = list1.split(":"), but then I think it is impossible to retrieve the "key" for this list, as there are multiple colons :
What is the most pythonic way to do this?
You can specify a maximum number of times to split with the second argument to split.
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict(item.split(':', 1) for item in list1)
Result:
>>> import pprint
>>> pprint.pprint(d)
{'CB': 'E:OWTOWTW',
'DS': 'f:115.5',
'EW': 'EE:KJERWEWERKJWE',
'GR': 'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7',
'MA': 'A:0XT:i:0',
'MW': 'AA:0',
'PP': 'E:A,A<F<AF',
'SX': 'F:-111'}
If you'd like to keep track of values for non-unique keys, like 'EW:G:B<<LADHFSSFAFFF' and 'EW:EE:KJERWEWERKJWE', you could add keys to a collections.defaultdict:
import collections
d = collections.defaultdict(list)
for item in list1:
k,v = item.split(':', 1)
d[k].append(v)
Result:
>>> pprint.pprint(d)
{'CB': ['E:OWTOWTW'],
'DS': ['f:115.5'],
'EW': ['G:B<<LADHFSSFAFFF', 'EE:KJERWEWERKJWE'],
'GR': ['A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7'],
'MA': ['A:0XT:i:0'],
'MW': ['AA:0'],
'PP': ['E:A,A<F<AF'],
'SX': ['F:-111']}
You can also use str.partition
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict([t for t in x.partition(':') if t!=':'] for x in list1)
# or more simply as TigerhawkT3 mentioned in the comment
d = dict(x.partition(':')[::2] for x in list1)
for k, v in d.items():
print('{}: {}'.format(k, v))
Output:
MW: AA:0
CB: E:OWTOWTW
GR: A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7
PP: E:A,A<F<AF
EW: EE:KJERWEWERKJWE
SX: F:-111
DS: f:115.5
MA: A:0XT:i:0
dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}
L = ['UUU', 'GUG', 'GUU']
As you see each elements of list(L) are in dictionary as keys. Now i want to replace each elements of L by its corresponding values. Output would be:
output = ['F','V']
How can i do that?
One way would be to decompose the keys into individual elements, and create a new dict from those:
new_dic = {}
for k, v in dic.items():
for sub_k in k:
new_dic[sub_k] = v
Now it's a simple matter of looping through the list:
output = [new_dic[i] for i in L]
and you can de-duplicate with set:
output = list(set(output))
Using list compression:
In [1]: dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}
In [2]: L = ['UUU', 'GUG', 'GUU']
In [3]: list(set([v for k,v in dic.items() for x in L if x in k]))
Out [3]: ['V', 'F']
Example:
list1 =['a','b','c','d']
new_list = []
dict = {'a':24, 'b':53 ,'c':26, 'd':9}
How would I take list1 and append the associated values of dict into new_list, so as to produce this:
new_list = [24,53,26,9]
Don't use 'dict' as a variable name, it will shadow the builtin dict() function.
list1 =['a','b','c','d']
d = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = [d[k] for k in list1]
assert new_list == [24, 53, 26, 9]
Assuming all the elements in list1 are keys in dict, this is the simplest solution I can think of :
list1 =['a','b','c','d']
new_list = []
dict = {'a':24, 'b':53 ,'c':26, 'd':9}
for it in list1:
new_list.append(dict[it])
list1 =['a','b','c','d']
d = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = map(lambda x: d[x], list1)
or if you really need to append instead of replacing:
new_list.extend(map(lambda x: d[x], list1))
What about this?
for key in list1:
new_list.append(dict[key])
print list1
Example output:
[24, 53, 26, 9]
Try this:
lst = ['a','b','c','d']
dct = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = [dct[k] for k in lst]