Create dictionaries from the lists - python

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

Related

How to replace a numerical value in a Python list

So I got this list of lists:
lst = [[0,1],2,[3]]
and I got a list of tuples:
lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]
I want to replace values inside lst with the index 0 value of each of the tuples in lst_2, and the tuple taken depends on the numerical value in lst. So it becomes:
lst = [["x1","x2"], "x3", ["x4"]]
Please don't roast me thanks so much
Try this:
lst = [[0,1],2,[3]]
lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]
res = []
for l in lst:
if isinstance(l, list):
res += [[lst_2[i][0] for i in l]]
else:
res += [lst_2[l][0]]
print(res)
Or with List Comprehensions:
res = [[lst_2[i][0] for i in l] if isinstance(l, list) else lst_2[l][0] for l in lst]
[['x1', 'x2'], 'x3', ['x4']]
You could use recursion to allow lst to have deeper levels of nesting:
def produce(template, data):
return [
produce(nested, data) for nested in template
] if isinstance(template, list) else data[template][0]
# Example
lst = [[0,[1]],2,[3]]
lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]
result = produce(lst, lst_2)

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]

removing and storing list from dictionary

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

How would I print things from a dictionary line by line?

So i have (below) which cleans up my list
def cleanGpaList(gpalist):
mylist = []
for i in gpalist:
b = i.strip()
c = b.split()
mylist.append(c)
return mylist
And (below) which sums up the values of keys that repeat. For example ['Bob','1.0'] and ['Bob', '2.1'] and gives me ['Bob', '3.1']
def dictGpa(cleanList):
diction = {}
for item in cleanList:
if item[0] in diction:
diction[item[0]] += float(item[1])
else:
diction[item[0]] = float(item[1])
diction2 = ', '.join(map(str,diction.keys()))
return (diction2)
Now I am trying to write a final function that prints from the dictionary line by line and the keys and the values.
'Bob' '3.1'
'xname' 'xnumber'
I have this, but it keeps giving me TypeError: string indices must be integers
def printCumulative(myDict):
for x in myDict:
print(x)
for y in myDict[x]:
print(y,' ',myDict[x][y])
To print keys and values you can use simple for:
for k,v in myDict.items():
print(k,v)

What is the fastest way to compare two lists with thounsands of entries?

I have
list1 = ["value1;value2;value3;value4;fdsa",]
list2 = ["value1;value2;value3;value4;asdf",]
What I need to do is go through each list2 entry, compare values with index 0,1,2,3 and if they match - use the fourth entry in another method.
Right now I have something like this:
for entry1 in list1:
for entry2 in list2:
if entry2.split(';')[0] == entry1.split(';')[0]: #... etc, compare first 3 values
print(entry2.split(';')[4]) # edited out my code
#do stuff
This obviously works, but it is incredibly slow. I am using Python 2.78
Firstly create a dictionary from list2's items with first four items as keys and the 5th item as value.
dct = dict(x.rsplit(';', 1) for x in list2)
And then loop over list1 and check if the key exist in the above dict:
for x in list1:
k, v = x.rsplit(';', 1)
if k in dct:
val = dct[k]
#do something with val
In case list2 contains repeated keys with different values then you may need to store them in a list:
from collections import defaultdict
d = defaultdict(list)
for x in list2:
k, v = x.rsplit(';', 1)
d[k].append(v)
for x in list1:
k, v = x.rsplit(';', 1)
for val in d[k]:
#do something with val
You are splitting the entries from list1 multiple times. If you split them once and store the result in a variable, you can reuse it in the inner loop.
Try like this:-
colon_sep_list1=list1.split(";")
colon_sep_list2=list2.split(";")
for index in range(len(colon_sep_list2)):
if index <=len(colon_sep_list1):
if colon_sep_list1[index]==colon_sep_list2[index]:
print colon_sep_list2[4]
break
For avoiding to split the list2 entries every time for compare with list1 entries store the split list in a separate variable and work with them :
>>> l2=map(lambda x:x.split(';'),list2)
>>> [j[4] for i in list1 for j in l2 if i.split(';')[0] == j[0]]
['asdf']
Benchmarking :
list1 = ["value1;value2;value3;value4;fdsa",]
list2 = ["value1;value2;value3;value4;asdf",]
def test1():
l2=map(lambda x:x.split(';'),list2)
new=[j[4] for i in list1 for j in l2 if i.split(';')[0] == j[0]]
def test2():
new=[]
for entry1 in list1:
for entry2 in list2:
if entry2.split(';')[0] == entry1.split(';')[0]: #... etc, compare first 3 values
new.append(entry2.split(';')[4]) # edited out my code
#do stuff
if __name__ == '__main__':
import timeit
print 'test 1 : ',timeit.timeit("test1()", setup="from __main__ import test1")
print 'test 2 : ',timeit.timeit("test2()", setup="from __main__ import test2")
result :
test 1 : 1.24494791031
test 2 : 1.34099817276

Categories