Count values by key in dictionary - python

I look for something that will count values in dict (automatically)without use a list of element
d = {}
d["x1"] = "1"
{'x1':'1'}
d["x1"] = "2"
{'x1':'2'}
d["x1"] = "3"
{'x1':'3'}
d["x2"] = "1"
{'x1':'3', 'x2':'1'}
ect..
I try create a list them using
for x in list:
d[x] = list.count(x)
But when I created a list , I receive a memory error

Are you sure you want to use a dict to do it? It seems a Counter or a defaultdict suits your need more.
>>> d = collections.Counter()
>>> d['x1'] += 1
>>> d
Counter({'x1': 1})
>>> d['x1'] += 1
>>> d
Counter({'x1': 2})
>>> d['x2'] += 1
>>> d
Counter({'x1': 2, 'x2': 1})
You could also convert a sequence to a counter:
>>> collections.Counter(['x1', 'x1', 'x2'])
Counter({'x1': 2, 'x2': 1})

Use a defaultdict:
>>> d = defaultdict(int)
>>> d['foo'] += 1
>>> d['foo'] += 1
>>> d['bar'] += 1
>>> for i in d:
... print i,d[i]
...
foo 2
bar 1

You can use dict in the following manner -
d['x1'] = d.get('x1', 0) + 1
The second argument in get specifies the object to return if the key supplied in the first argument is not found.
Applying this on your example:
from pprint import pprint
d = {}
d['x1'] = d.get('x1', 0) + 1
d['x1'] = d.get('x1', 0) + 1
d['x1'] = d.get('x1', 0) + 1
d['x2'] = d.get('x2', 0) + 1
pprint(d) # will print {'x1': 3, 'x2': 1}

Related

Python count occurence of a string without overlapping from a string

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)

how do you build nested defaultdicts in Python with objects of a different type

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

searching element of 1-D list in 2-D list

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})

python: directory with values other then occurrence of keys

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

Python Compare Two Key/Value Pairs

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!

Categories

Resources