test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
data = test.count(search)
data
When I run this, I get
TypeError: must be str, not list
I want to know how I can count when using [ ] instead of a single string.
you can use a loop on search
data = [test.count(s) for s in search]
count() takes a str parameter and not a list.
test = "aaaabbcdeiiifkdkkffkk"
data = test.count("a")
More info here.
You need to loop throught the search list, so this list comprehension can do the job:
[test.count(i) for i in search]
But i prefer this
test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
data = {}
for i in search:
data.update({i: test.count(i)})
Or you can use a one liner.
data = {c: test.count(c) for c in search}
Out: {'a': 4, 'c': 1, 'd': 2, 'e': 1}
You can use multiple ways to find out, to count the number of occurrence, .count() only takes one str value
Method 1: Using List Comprehension
data = [test.count(s) for s in search]
Method 2: Using Map
data = list(map(test.count,search))
You can create multiple other methods to do so referring the above.
Using collections.Counter
Ex:
from collections import Counter
test = "aaaabbcdeiiifkdkkffkk"
search = ["a", "c", "d", "e"]
count_data = Counter(test) #--> Counter({'k': 5, 'a': 4, 'i': 3, 'f': 3, 'b': 2, 'd': 2, 'c': 1, 'e': 1})
for i in search:
print(i, count_data.get(i, 0))
Output:
a 4
c 1
d 2
e 1
Loop over search strings and apply count to each one.
data = []
pos = 0
for s in search:
data[pos] = test.count(s)
pos = pos + 1
print(data)
Related
This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 10 months ago.
i was trying to keep count of each item in list in python and want to convert it into key-value pairs like json so i can able to iterate over it to present it on frontend using django.
list = ["a" , "a", "c", "b", "c", "d"]
here same i want this list into key value pairs with counting of each item in list
list = [{ "name":"a" , "count":2 } , { "name":"c" , "count":2 , ......}]
Use a set to count the number of each element in the list
l = ["a" , "a", "c", "b", "c", "d"]
d = {val: l.count(val) for val in set(l)}
this will give you :
{'c': 2, 'a': 2, 'b': 1, 'd': 1}
If you want to format the dict as you wrote it in your message (even though it's really inefficient), you can write it like that :
d = [{'name': val, 'count': l.count(val)} for val in set(l)}]
data = ["a" , "a", "c", "b", "c", "d"]
count_list=[{"name":d,"count": data.count(d)} for d in set(data)]
Probably the easiest way to do this:
def dict_count(list):
dict_tot = {}
for i in liste:
dict_tot[i] = liste.count(i)
print(dict_tot)
I have one dataset in a list form and I want to convert it into another dataset under certain conditions.
Conditions
"a" = 1
"b" = 2
"c" = 3
input_list = ["a", "b", "c"]
# something happens
output_list = [1, 2, 3]
What to do?
Represent your set of conditions in a dictionary:
conditions = {
"a": 1,
"b": 2,
"c": 3
}
Use that dictionary in order to generate the output:
input_list = ["a", "b", "c"]
output_list = [conditions[x] for x in input_list]
What you want to achieve is a mapping.
Your conditions are a map, dictionary (Python lingo) or hash-table.
Each value there (like 1) corresponds to a key in the dataset (like "a").
To represent this mapping you can use a table-like datastructure that maps a key to a value. In Python this datastructure is called a dictionary:
mapping = {"a": 1, "b": 2, "c": 3} # used to translate from key to value (e.g. "a" to 1)
input_list = ["a", "b", "c"]
# something happens
output_list = []
for v in input_list:
mapped_value = mapping[v] # get the corresponding value, translate or map it
print(v + " -> " + mapped_value)
output_list.append(mapped_value)
print(output_list) # [1, 2, 3]
See also
Map (mathematics) - Wikipedia
Convert numbers into corresponding letter using Python
I want to write a function that takes a file name and a list as arguments and reads the text within the corresponding file, then creates a dictionary whose keys are the characters of the provided list, and the values are the counts of these characters within the text. If the file does not exist, then the function returns an empty dictionary.
For example:
sample.txt
This is an example sentence
This is yet another sentence
Here is the code that I've written so far:
def text2dict(filename, characters):
count_word = dict()
for char in characters:
count_word[char] = 0
with open(filename) as input_text:
text = input_text.read()
words = text.lower().split()
for word in words:
_word = word.strip('.,:-)()')
if word in count_word:
count_word[_word] += 1
return count_word
file_name = "sample.txt"
list_char = ["a", "b", "c", "t"]
text2dict(file_name, list_char)
Expected Output:
{'a':3, 'b':0, 'c':2, 't':6}
The output I got:
{'a': 0, 'b': 0, 'c': 0, 't': 0}
You can use "".count() for that. Also there is no need to pre-fill the dictionary anymore, as we are not using iadd.
def text2dict(filename, characters):
count_letters = dict()
with open(filename) as input_text:
text = input_text.read()
for k in characters:
count_letters[k] = text.count(k)
return count_letters
With this you get the expected result
>>> file_name = r"sample.txt"
>>> list_char = ["a", "b", "c", "t"]
>>> print(text2dict(file_name, list_char))
{'a': 3, 'b': 0, 'c': 2, 't': 6}
You are checking if a word is existing in the dictionnary, but the dictionnary only contains letters.
Spoiler:
if you want a working version right away:
def text2dict(filename, characters):
count_word = dict()
for char in characters:
count_word[char] = 0
with open(filename) as input_text:
text = input_text.read()
words = text.lower().split()
for word in words:
_word = list(word)
for i in _word:
if i in count_word:
count_word[i] += 1
return count_word
You can use collections.Counter().
from collections import Counter
file = open('test.txt')
rows = [row.strip().replace(' ','').lower() for row in file]
wanted = ["a", "b", "c", "t"]
finalDict = {letters:dict(Counter(r)).get(letters,0) for r in rows for letters in wanted}
output
{'a': 1, 'b': None, 'c': 1, 't': 4}
Shortened down all the way, for funnsies
from collections import Counter
finalDict = {letters:dict(Counter(r)).get(letters) for r in [row.strip().replace(' ','').lower() for row in open('test.txt')] for letters in ["a", "b", "c", "t"]}
I am merging two json in python
I'm doing
import json
json_obj = json.dumps({"a": [1,2]})
json_obj1 = json.dumps({"a": [3,4]})
json_obj += json_obj1
print(json_obj)
I am expecting the output as
{"a": [1, 2,3,4]}
but i got
{"a": [1, 2]}{"a": [3, 4]}
How to get the earlier one?
In json module, dumps convert python object to a string, and loads convert a string into python object. So in your original codes, you just try to concat two json-string. Try to code like this:
import json
from collections import defaultdict
def merge_dict(d1, d2):
dd = defaultdict(list)
for d in (d1, d2):
for key, value in d.items():
if isinstance(value, list):
dd[key].extend(value)
else:
dd[key].append(value)
return dict(dd)
if __name__ == '__main__':
json_str1 = json.dumps({"a": [1, 2]})
json_str2 = json.dumps({"a": [3, 4]})
dct1 = json.loads(json_str1)
dct2 = json.loads(json_str2)
combined_dct = merge_dict(dct1, dct2)
json_str3 = json.dumps(combined_dct)
# {"a": [1, 2, 3, 4]}
print(json_str3)
json.dumps() converts a dictionary to str object, not a json(dict) object.
So, adding some dumps statement in your code shows that the type is changed to str after using json.dumps() and with + you are effectively concatenating the two string and hence you get the concatenated output.
Further, to merge the two dictionaries for your simple case, you can just use the append:
import json
json_obj = json.dumps({"a": [1,2]})
json_obj1 = json.dumps({"a": [3,4]})
print(type(json_obj1)) # the type is `str`
json_obj += json_obj1 # this concatenates the two str objects
json_obj = {"a": [1,2]}
json_obj1 = {"a": [3,4]}
json_obj["a"].extend(json_obj1["a"])
print(json_obj)
I suggest you to study basic fundamental of Python for your own sake as you don't seem to understand why your code wouldn't work.
import json
# We have two dictionaries to combine
json_obj_1 = {"a": [1,2], "b":[2,3], 'c': [1,2,3]}
json_obj_2 = {"a": [3,4], 'd':[4,2], 'e': [4,2,2]}
Merged dictionary will be stored here
hold_json_obj = {}
Don't worry, it's not actually that complicated. Read the code line by line with comments attached and you'll understand.
# We'll loop through every item in the json_obj_1 dictionary
for item_1 in json_obj_1:
# We'll also loop through every item in the json_obj_2 dictionary
for item_2 in json_obj_2:
# Now let's compare whether they are the same KEYS (not values)
if item_1 == item_2:
# if they match, we create a list to store the array
hold_array = []
hold_array.extend(json_obj_1[item_1])
hold_array.extend(json_obj_2[item_1])
# finally putting the array to our hold_json_obj
hold_json_obj[item_1] = hold_array
else:
# if they don't match, check if the key already exists in the
# hold_json_obj because we might be iterating json_obj_2 for the second time.
if item_2 not in hold_json_obj:
#add the ummatched array to hold_json_obj
hold_json_obj[item_2] = json_obj_2[item_2]
Now simply update json_obj_1 with the update method. The update function is required because if json_obj_1 has keys that json_obj_2 doesn't then we may have missed them out in the above loops.
json_obj_1.update(hold_json_obj)
print(json_obj_1)
This is what the print displays.
{'a': [1, 2, 3, 4], 'b': [2, 3], 'c': [1, 2, 3], 'd': [4, 2], 'e': [4, 2, 2]}
So I want my end output to look like this:
answer = {'A':{1,2,3,4},'B':{1,2,3,4}}
How can I do this? I have a few questions though.
How do I make a dictionary without a key pair value. Like {1,2,3,4}
How do I append the {1,2,3,4} to a key ('A').
How do I append the A into the main dictionary(answer)
Essentially I am trying to make this bit in a loop 'A':{1,2,3,4}. Then outside the loop append it to answer.
{1,2,3,4} is a set, not a dict.
You can add the A key and its value (the set) like so:
answer = {}
answer["A"] = {1,2,3,4}
If you have a set, you can add:
>>> s = {1,2}
>>> s
{1, 2}
>>> s.add(3)
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
To iterate:
>>> for item in answer['A']:
... print(item)
...
1
2
3
4
If you want to build a dictionary like that given a list of keys and a set you can do:
list_of_keys = ["A", "B", "C"]
some_set = {1,2,3,4}
my_dict = {key: some_set for key in list_of_keys}
Is there a specific reason why you want to use dictionary and append values into it?
You can use a dictionaries of list:
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = []
# Inner Loop
answer[i].append(j) # j = 1, 2, 3, 4
print(answer) # {'A':[1,2,2,3,4],'B':[1,1,2,3,4]}
If you do not want duplicates then you can use a set instead of a list.
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = set()
# Inner Loop
answer[i].add(j) # j = 1, 2, 3, 4
print(answer) # {'A':(1,2,3,4),'B':(1,2,3,4)}
Hope this helps, Cheers!