I was trying to find the occurrence of every 2 consecutive characters from a string.
The result will be in a dictionary as key = 2 characters and value = number of occurrence.
I tried the following :
seq = "AXXTAGXXXTA"
d = {seq[i:i+2]:seq.count(seq[i:i+2]) for i in range(0, len(seq)-1)}
The problem is that the result of XX should be 3 not 2 .
You can use collections.Counter.
from collections import Counter
seq = "AXXTAGXXXTA"
Counter((seq[i:i+2] for i in range(len(seq)-1)))
Output:
Counter({'AX': 1, 'XX': 3, 'XT': 2, 'TA': 2, 'AG': 1, 'GX': 1})
Or without additional libraries. You can use dict.setdefault.
seq = "AXXTAGXXXTA"
d = {}
for i in range(len(seq)-1):
key = seq[i:i+2]
d[key] = d.setdefault(key, 0) + 1
print(d)
I'm trying to rewrite the following code
dct = {}
x = 'x'
y = 'y'
z = 'z'
if x not in dct:
dct[x] = defaultdict(dict)
if y not in dct[x]:
dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))
dct[x][y][z]['b'][0]['g']+=1
Without the following lines:
if x not in dct:
dct[x] = defaultdict(dict)
if y not in dct[x]:
dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))
Ideally I would like to have syntax such as
dct = 'state what it is'
dct[x][y][z]['b'][0]['g']+=1
I wrote a customised implementation of defaultdict which can do this to an arbitrary depth, unlike the fixed depth from previous answers.
class DefaultDict(dict):
def __missing__(self, name):
rval=type(self)()
self.__setitem__(name, rval)
return rval
Here's some example usage:
>>> dct=DefaultDict()
>>> dct[0][1]['bees'][('any','hashable','object')]=2
>>> dct[0][1]['bees'][('any','hashable','object')]
2
>>> 0 in dct
True
>>> 1 in dct
False
>>> dct
{0: {1: {'bees': {('any', 'hashable', 'object'): 2}}}}
Use lambdas.
from collections import defaultdict as dd
dct = dd(lambda: dd(lambda: dd(int)))
dct["foo"][1][("a", 7)] += 1
I have two lists, one is of form:
A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]
I have to process such that final output is
C = A = [("qww",8),("ewq",20),("ert",4),("ask",11)]
for that I written code:
# in code temp_list is of form A
# in code total_list is of form B
# in code final is of form C
def ispresent(key,list):
for qwerty in list:
if qwerty == key:
return 1
else:
return 0
def indexreturn(key,list):
counter = 0
for qwerty in list:
if qwerty != key:
counter = counter + 1
else:
return counter
def mult_indexreturn(key,list):
for i in range(len(list)):
if key == list[i][0]:
return i
final = map(lambda n1, n2: (n1,n2 ), temp_list,[ 0 for _ in range(len(temp_list))])
for object2 in total_list:#****
for object1 in temp_list:
if object2 == object1:
final[ indexreturn(object2,final) ][1] = final[ indexreturn(object2, final) ][1] + object2[mult_indexreturn(object2,total_list)][1]#total_list[ mult_indexreturn(object2,total_list) ][1]
print(final)
it should give output as C type list, but giving nothing
but C = [("qww",0),("ewq",0),("ert",0),("ask",0)]
according to me the main problem is in my looping part ( with **** comment), is there problem with logic or something else.
I gave in lot of codes, so that you can understand how my code working
You can build a dictionary using the method fromkeys() and subsequently you can use the for loop to accumulate integers:
A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]
C = dict.fromkeys(A, 0)
# {'qww': 0, 'ewq': 0, 'ert': 0, 'ask': 0}
for k, v in B:
C[k] += v
C = list(C.items())
# [('qww', 8), ('ewq', 30), ('ert', 4), ('ask', 11)]
Try this:
from collections import defaultdict
result = defaultdict(int)
for i in A:
result[i] = sum([j[1] for j in B if j[0] == i])
then tuple(result.items()) will be your out put.
Or you can do it in just one line:
result = tuple({i:sum([j[1] for j in B if j[0] == i]) for i in A}.items())
Using collection.defaultdict
Ex:
from collections import defaultdict
A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]
result = defaultdict(int)
for key, value in B:
if key in A: #Check if Key in A.
result[key] += value #Add Value.
print(result)
Output:
defaultdict(<type 'int'>, {'qww': 8, 'ert': 4, 'ewq': 30, 'ask': 11})
How can I make a directory have values count from a list that is associated with the Keys, opposed to the occurrences of a particular Key.
EXAMPLE: I have two lists, One is of strings, and one is of a values for each string.
say:
strings = ['me', 'you', 'me', 'her','her']
values = [1,20,6,35,5]
and I want:
directory = {'me':7, 'you':20, 'her':40}
This is how I have been making directories:
d = {}
for i in list:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
valueKeys = zip(d.values(),d.keys())
value = d.values()
keys = d.keys()
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for x, y in zip(strings, values):
... d[x] += y
...
>>> d
defaultdict(<class 'int'>, {'you': 20, 'her': 40, 'me': 7})
The resulted defaultdict object can act as plain dict:
for key in d:
print(key, d[key])
Output:
me 7
her 40
you 20
#x=numbers
#list = names
d = {}
for i in list:
if i in d:
d[i] = d[i]+x[list.index(i)]
else:
d[i] = x[list.index(i)]
valueKeys = zip(d.values(),d.keys())
value = d.values()
keys = d.keys()
This was how I solved it
Ive got two sets of key value pairs that look like this:
tom = {'coffee': 2, 'hotdog': 1}
and another like this:
namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
Id like to compare whenever a key associated with 'tom' is the same as a value in 'namcat', and if so add 1 to a running total. I think its iterating over key-value pairs with lists that is causing me issues.
for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
Demo:
>>> hotdog = 1
>>> coffee = 2
>>> foodstand = 6
>>> breakfast = 10
>>> tom = {'coffee': 2, 'hotdog': 1}
>>> namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
>>> running_total = 0
>>> for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
>>> running_total
2
This should do it. Hope it helps!