removing and storing list from dictionary - python

In python,
I have a dictionary composed of the following:
[ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ].
I'm trying to remove the keyed FOXP2_DOG from the dictionary and place it in a new dictionary alone. I've tried different methods: del and .remove to no avail.

like this:
>>> my_list= [ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ]
>>> my_dict = dict(my_list)
>>> my_dict
{'FOXP2_RAT': 'AminoAcidSequence2', 'FOXP2_MOUSE': 'AminoAcidSequence1', 'FOXP2_DOG': 'AminoAcidSequence3'}
>>> my_new_dict = {}
>>> my_new_dict['FOXP2_MOUSE'] = my_dict.pop('FOXP2_MOUSE')
>>> my_dict
{'FOXP2_RAT': 'AminoAcidSequence2', 'FOXP2_DOG': 'AminoAcidSequence3'}
>>> my_new_dict
{'FOXP2_MOUSE': 'AminoAcidSequence1'}

my_data = [ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ]
def custom_filter_data(data, key):
final_res = []
for i in range(len(data)):
if data[i][0] == key:
final_res.append(data[i])
del data[i]
return data, final_res
results = custom_filter_data(my_data,'FOXP2_DOG')
old = results[0]
new = results[1]
print old
print new

Related

Create dictionaries from the lists

I have a list "testlist" that contains 4x sublists
[
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
I want to get following dictionary from the "testlist"
{group1:[name1,name2], group2:[name3,name4]}
I have this little piece of code here which is taking "group" elements from each sublist and then updates dictionary with taken elements as keys. I'm stuck with is how to fill the values of these keys ?
def test():
dic={}
testlist = [
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
for each in testlist:
dic.update{each[3]:[]}
Considering the items inside each sublist of testlist are string, try this :
dic = {i : [j[0] for j in testlist if i==j[3]] for i in set([k[3] for k in testlist])}
Here is the same code in details :
unique_fourth_items = []
for i in testlist:
unique_fourth_items.append(i[3])
unique_fourth_items = set(unique_fourth_items)
dic = {}
# Check in testlist for each item of unique_fourth_items list
for i in unique_fourth_items:
temp = []
for j in testlist:
if j[3] == i:
temp.append(j[0])
dic[i] = temp
Using a 'traditional' loop over the list (assuming name1, ip1, etc. are defined somewhere):
def test():
dic = {}
testlist = [
[name1, ip1, mask1, group1],
[name2, ip2, mask2, group1],
[name3, ip3, mask3, group2],
[name4, ip4, mask4, group2]
]
for each in testlist:
if each[3] not in dic:
dic[each[3]] = []
dic[each[3]].append(each[0])
return dic

Add Multiplie values in list for the same key using python

Please check the below code and my output. I have run my code i got the below output but i want Expected Result.
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
Expected Result is :-
{
"ABCD": "SATARA",
"XYZ": ["MUMBAI", "PUNE"]
"PQR": "43566",
"LMN": "455667"
}
My Code :-
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
for each_split_data in list_data:
split_by_colon = each_split_data.split(":")
if split_by_colon[0] is not '':
if split_by_colon[0] in splittded_data_dict:
# append the new number to the existing array at this slot
splittded_data_dict[split_by_colon[0]].append(split_by_colon[1])
else:
# create a new array in this slot
splittded_data_dict[split_by_colon[0]] = [split_by_colon[1]]
print(json.dumps(splittded_data_dict, indent=2), "\n")
My OUTPUT :-
{
"ABCD": [
"SATARA"
],
"REF": [
"MUMBAI.",
"PUNE"
],
"PQR": [
"43566"
],
"LMN": [
"455667"
]
}
How can i solve the above problem?
The best thing to do in my opinion would be to use a defaultdict from the collections module. Have a look:
from collections import defaultdict
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
res = defaultdict(list)
for item in list_data:
key, value = item.split(':')
res[key].append(value)
which results in:
print(res)
# defaultdict(<class 'list'>, {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']})
or cast it to dict for a more familiar output:
res = dict(res)
print(res)
# {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']}
From what I understand by the description of your problem statement, you want splittded_data_dict to be a dictionary where each value is a list
For this purpose try using defaultdict(). Please see the example below.
from collections import defaultdict
splittded_data_dict = defaultdict(list)
splittded_data_dict['existing key'].append('New value')
print(splittded_data_dict)
You can use the isinstance function to check if a key has been transformed into a list:
d = {}
for i in list_data:
k, v = i.split(':', 1)
if k in d:
if not isinstance(d[k], list):
d[k] = [d[k]]
d[k].append(v)
else:
d[k] = v
d becomes:
{'ABCD': 'SATARA', 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': '43566', 'LMN': '455667'}
Let's append all possible key values from the string items in the list_data. Get the list of unique items. Now loop through the list_data and check if the first item of the ":" split string matched with the list a and if matches append to a temporary list and at last assign that temporary list as the value to the key of the item in the list a.
Here is oneliner using dict comprehension and list comprehension simultaneously :
c = {i : [j.split(":")[1] for j in list_data if j.split(":")[0] == i ][0] if len([j.split(":")[1] for j in list_data if j.split(":")[0] == i ])==1 else [j.split(":")[1] for j in list_data if j.split(":")[0] == i ] for i in list(set([i.split(":")[0] for i in list_data]))}
Output should be :
# c = {'LMN': '455667', 'ABCD': 'SATARA', 'PQR': '43566', 'XYZ': ['MUMBAI', 'PUNE']}
Here is the long and detailed version of the code :
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
a = []
for i in list_data:
a.append(i.split(":")[0])
a = list(set(a))
b = {}
for i in a:
temp = []
for j in list_data:
if j.split(":")[0] == i:
temp.append(j.split(":")[1])
if len(temp) > 1:
b[i] = temp
else:
b[i] = temp[0]

Append list based on another element in list and remove lists that contained the items

Let's say I have two lists like this:
list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]
I want to combine the items together by their holder (i.e 'Robert') only when they are in separate lists. Ie in the end list_all should contain:
list_all = [[['some_name','something_else'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]
What is a fast and effective way of doing it?
I've tried in different ways but I'm looking for something more elegant, more simplistic.
Thank you
Here is one solution. It is often better to store your data in a more structured form, e.g. a dictionary, rather than manipulate from one list format to another.
from collections import defaultdict
list_all = [[['some_item'],'Robert'],
[['another_item'],'Robert'],
[['itemx'],'Adam'],
[['item2','item3'],'Maurice']]
d = defaultdict(list)
for i in list_all:
d[i[1]].extend(i[0])
# defaultdict(list,
# {'Adam': ['itemx'],
# 'Maurice': ['item2', 'item3'],
# 'Robert': ['some_item', 'another_item']})
d2 = [[v, k] for k, v in d.items()]
# [[['some_item', 'another_item'], 'Robert'],
# [['itemx'], 'Adam'],
# [['item2', 'item3'], 'Maurice']]
You can try this, though it's quite similar to above answer but you can do this without importing anything.
list_all = [[['some_item'], 'Robert'], [['another_item'], 'Robert'], [['itemx'], 'Adam'], [['item2', 'item3'], 'Maurice']]
x = {} # initializing a dictionary to store the data
for i in list_all:
try:
x[i[1]].extend(i[0])
except KeyError:
x[i[1]] = i[0]
list2 = [[j, i ] for i,j in x.items()]
list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice']]
dict_value = {}
for val in list_all:
list_, name = val
if name in dict_value:
dict_value[name][0].extend(list_)
else:
dict_value.setdefault(name,[list_, name])
print(list(dict_value.values()))
>>>[[['some_item', 'another_item'], 'Robert'],
[['itemx'], 'Adam'],
[['item2', 'item3'], 'Maurice']]

Find matching keywords in nested dictionary

I have a nested dictionary like:
data = {
'level1a': {'level2a':[1,2,3]},
'level1b': {'level2b':[4,5,6]},
'level1c': {'level2a':[7,8,9]}
}
Now i would like to find and sum up the 2 lists with the same level 2 keyword ('level2a'). The result should be something like:
[8, 10, 12]
Is there some efficient way to do that?
Something like this:
from collections import Counter
from operator import add
data = {
'level1a': {'level2a':[1,2,3]},
'level1b': {'level2b':[4,5,6]},
'level1c': {'level2a':[7,8,9]}
}
c = Counter()
dic = {}
for k,v in data.iteritems():
for k1, v1 in v.iteritems():
c[k1] += 1
val = dic.setdefault(k1, [0]*len(v1))
dic[k1] = map(add, v1, val)
for k,v in c.iteritems():
if v > 1:
print dic[k]
Output:
[8, 10, 12]
Try:
result=[]
for first_key, first_value in data.iteritems():
for second_key, second_value in first_value.iteritems():
if second_key == 'level2a':
if result == []:
result += second_value
else:
result=[result[i] + value for i,value in enumerate(second_value)]
This will iterate through each of them checking for the correct key in thes second level dicts. The if/else loop determines if any items have been added to the result already. If so, it will increment the values according to the next list in 'level2a'. This also assumes that all second level lists are the same length, otherwise you will have trailing values in result that won't be incremented.
You could try something like this:
>>> data = {
... 'level1a': {'level2a':[1,2,3]},
... 'level1b': {'level2b':[4,5,6]},
... 'level1c': {'level2a':[7,8,9]}
... }
>>>
>>> def sum_matches(data, match):
... inner = data.itervalues()
... matches = (x[match] for x in inner if match in x)
... return [sum(x) for x in zip(*matches)]
...
>>>
>>> sum_matches(data, 'level2a')
[8, 10, 12]

Dictionary out of list in python

How can I create a dictionary out of the a in python?
If I have a list like this:
a = ["Albert Einstein", "Nils Bohr"]
And I want it to become this:
b = {'Albert Eienstein': ['Albert', 'Eienstein'], 'Neils Bohr': ['Neils', 'Bohr']}
lista = ["Albert Eienstein","Neils Bohr"]
dictb = {}
for elem in lista:
dictb[elem] = elem.split(' ')
print dictb
Output: {'Neils Bohr': ['Neils', 'Bohr'], 'Albert Eienstein': ['Albert', 'Eienstein']}
I don't understand your question. Are you saying that you want this?
list_of_lists = [['Albert', 'Einstein'], ['Neils', 'Bohr']]
Or this?
dict_of_lists = {'Albert Einstein':['Albert', 'Einstein'],
'Neils Bohr':['Neils', 'Bohr']}
Or are you saying you want to convert from one to the other?
>>> l = ["Albert Eienstein", "Neils Bohr"]
>>> d = dict((i, i.split()) for i in l)
>>> d
{'Neils Bohr': ['Neils', 'Bohr'], 'Albert Eienstein': ['Albert', 'Eienstein']}
Just put the list inside the other, ie
scientists = [["Albert","Einstein"],["Neils","Bohr"]]

Categories