This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 4 years ago.
I have 5 set of lists and some of strings in those lists are repetitive
now! I wanna know the number of repetition! for example the word "A" is in all of my lists by "B" is just in "3" or "C" is in 4 of them.
How can I sort this problem, by using remove() I faced to wrong answer
Thank you in advance!
Take a look at Counter
from collections import Counter
a = ['a','a','b','b']
b = ['b','b','c','d']
c = a+b
cnt = Counter()
for x in c:
cnt[x] +=1
print(cnt)
Counter({'a': 2, 'b': 4, 'c': 1, 'd': 1})
The above will get you counts of each but it seems like you're more concerned at a list level.
from collections import defaultdict
f = defaultdict(list)
a = ['a','a','b','b']
b = ['b','b','c','d']
c = ['e','f','g','h']
d = a + b + c
for i in d:
f[i] = 0
if i in b:
f[i] += 1
if i in c:
f[i] +=1
if i in a:
f[i] +=1
print (f)
defaultdict(list,
{'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1})
Related
This question already has answers here:
How do I create a nested dict from a dict by splitting the keys on a delimiter in python?
(4 answers)
Closed 1 year ago.
I want to write a method which takes a dict in the form of {a: 1, b-c: 2, b-d: 3, e-f-g: 4} and returns {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4}}}. Basically split the keys containing - into subdicts. I've tried to do it iteratively and recursively but I got stuck. Any tips?
You can use collections.defaultdict with recursion:
from collections import defaultdict
d = {'a': 1, 'b.c': 2, 'b.d': 3, 'e.f.g': 4}
def group(d):
nd = defaultdict(list)
for [a, *b], c in d:
nd[a].append([b, c])
return {a:b[0][-1] if not any(j for j, _ in b) else group(b) for a, b in nd.items()}
result = group([[a.split('.'), b] for a, b in d.items()])
Output:
{'a': 1, 'b': {'c': 2, 'd': 3}, 'e': {'f': {'g': 4}}}
I want to convert a list to a default dictionary to have a default value of 0 in case the key doesn't have any value (from the list).
list : order = ['a',1,'b',2,'c']
what I did using ZIP :
it = iter(order)
res_dict = dict(zip(it,it))
print(res_dict)
but it excludes c as a key, as the list doesn't have the next index after c.
Result I got : {'a': 1, 'b': 2}
Result i want : {'a': 1, 'b': 2, 'c': 0}
You might want to consider using itertools and .zip_longest().
For example:
import itertools
l = ['a',1,'b',2,'c']
d = dict(itertools.zip_longest(l[::2], l[1::2], fillvalue=0))
print(d)
Output:
{'a': 1, 'b': 2, 'c': 0}
This is working:
d = dict()
for i in range(len(order)):
if i%2==0 and i+1<len(order):
d[order[i]] =order[i+1]
elif i+2>(len(order)):
d[order[i]]=0
Result:
{'a': 1, 'b': 2, 'c': 0}
To solve the problem of two consequent keys you can use a custom function to split the list
def splitdefault(o):
i = 0
while i < len(o):
# there is a next element to check
if i + 1 < len(o):
# the next element is int
if isinstance(o[i + 1], int):
yield o[i], o[i + 1]
i += 2
else:
yield o[i], 0
i += 1
# i is the last element
else:
yield o[i], 0
i += 1
order = ["a", 1, "b", 2, "c", "d", 3, "e"]
for g in splitdefault(order):
print(g)
res_dict = dict(splitdefault(order))
print(res_dict)
Which produces
{'a': 1, 'b': 2, 'c': 0, 'd': 3, 'e': 0}
Cheers!
This question already has answers here:
Counting Letter Frequency in a String (Python) [duplicate]
(13 answers)
Closed 3 years ago.
I have a string l1 that for example contains the following content: aackcdldccc. I would like to count the number of times that each character occurs using dictionary. The required final result should be a dictionary like this:
a:2
c:5
k:1
d:2
l:1
How can I fix my code so it will work?
I use the following code and get error message:
l1= ('aackcdldccc')
print (l1)
d={}
print (len(l1))
for i in (range (len(l1))):
print (i)
print (l1[i])
print (list(d.keys()))
if l1[i] in list(d.keys()):
print ('Y')
print (l1[i])
print (list(d.keys())[l1[i]])
d1 = {l1[i]:list(d.values())[l1[i]+1]}
#print (d1)
#d.update (d1)
else:
print ('N')
d1={l1[i]:1}
d.update (d1)
Here is the error I get:
aackcdldccc
11
0
a
[]
N
1
a
['a']
Y
a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-185-edf313da1f8d> in <module>()
10 print ('Y')
11 print (l1[i])
---> 12 print (list(d.keys())[l1[i]])
13 #d1 = {l1[i]:list(d.values())[l1[i]+1]}
14 #print (d1)
TypeError: list indices must be integers or slices, not str
There are two ways to do this:
In [94]: s = 'aackcdldccc'
In [95]: collections.Counter(s)
Out[95]: Counter({'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1})
In [96]: d = {}
In [97]: for char in s:
...: d.setdefault(char, 0)
...: d[char] += 1
...:
In [98]: d
Out[98]: {'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1}
How can I iterate over only X number of dictionary items? I can do it using the following bulky way, but I am sure Python allows a more elegant way.
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
x = 0
for key in d:
if x == 3:
break
print key
x += 1
If you want a random sample of X values from a dictionary you can use random.sample on the dictionary's keys:
from random import sample
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
X = 3
for key in sample(d, X):
print key, d[key]
And get output for example:
e 5
c 3
b 2
This question already has answers here:
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
(22 answers)
Closed 5 years ago.
How to add the values of two dictionary ?
Ex :
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
result must be
c = {'a':11,'b':12,'c':21}
You can easily add two dictionaries by using Counter class of collections library for ex:
from collections import Counter
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
a = Counter(a)
b = Counter(b)
c = dict(a + b)
print c
OUTPUT
{'c': 21, 'b': 12, 'a': 11}
Next some please show some effort..
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
c = {k: a[k] + b[k] for k in a}
print(c) # {'c': 21, 'b': 12, 'a': 11}
The above works fine if we assume that a and b have the same keys.
If that is not the case, you can try the following:
a = {'a': 10, 'b': 11, 'c': 20, 'h': 5}
b = {'a': 1, 'b': 1, 'c': 1, 'd': 12}
all_keys = set(a.keys()) # in Python 3 it can be simplified as `all_keys = set(a)`
all_keys.update(b.keys()) # in Python 3 it can be simplified as `all_keys.update(b)`
c = {k: a.get(k, 0) + b.get(k, 0) for k in all_keys}
print(c) # {'c': 21, 'h': 5, 'a': 11, 'b': 12, 'd': 12}
Notice that i am using get on both dictionaries to skip the check on the existence of the key.