I'm creating a program that counts letters. I created two dictionaries that both have the same word and, because they are the same exact word, both have the same counter. I want to know how to merge the two dictionaries so that it updates the counters as well, but I consistently receive the result "NONE."
word = 'he'
word2 = 'he'
d1 = {}
d2 = {}
for letter in word:
if letter in d1:
d1[letter]+=1
else:
d1[letter] = 1
print(d1)
#That Outputs: {'h': 1, 'e': 1}
for letter in word2:
if letter in d2:
d2[letter]+=1
else:
d2[letter] = 1
print(d2)
#That Outputs {'h': 1, 'e': 1}
#That Outputs: None
#I want the outputs {'h': 2, 'e': 2}
You can concatenate strings and use a single dictionary:
word1 = 'he'
word2 = 'he'
common_dict = {}
for letter in word1 + word2:
if letter in common_dict:
common_dict[letter] += 1
else:
common_dict[letter] = 1
print(common_dict)
Also please never use a built-in name as a variable name. In your case, you used dict as a variable name
Related
This question already has answers here:
Counting letters with python
(3 answers)
Closed 2 years ago.
I have to write a Python program that takes a string as an input from the user and
I have this string:
Python programming is fun
I want to count the frequency of each character using the dictionary which should be:
{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}
I tried this:
string = input("Enter a string: ")
new_dict = {} #new_dict for frequency
lower_case = string.lower()
for key in lower_case:
if key in new_dict.keys():
new_dict[key] = new_dict[key] + 1
else:
new_dict[key] = 1
print(new_dict)
and the output came:
{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}
Here output is counting the spaces in the line. I want to remove the space from the output. What should I apply?
you can check if the character is a space, and if it is return to top of the loop
string = input("Enter a string: ")
new_dict = {} #new_dict for frequency
lower_case = string.lower()
for key in lower_case:
if key == " ":
continue # return to top of loop
if key in new_dict.keys():
new_dict[key] = new_dict[key] + 1
else:
new_dict[key] = 1
print(new_dict)
Or just remove the key after counter all characters (including spaces) by doing new_dict.pop(" ") after the loop.
You should remove the spaces from input_string, like
string = #input("Enter a string: ")
new_dict = {} #new_dict for frequency
lower_case = string.lower().replace(' ', '')
for key in lower_case:
if key in new_dict.keys():
new_dict[key] = new_dict[key] + 1
else:
new_dict[key] = 1
print(new_dict)
You can do string.replace(' ', '') and delete the spaces from the string.
you can replace the white-space at the very beginning:
string = input("Enter a string: ").replace(' ', '')
new_dict = {} # new_dict for frequency
lower_case = string.lower()
for key in lower_case:
if key in new_dict.keys():
new_dict[key] = new_dict[key] + 1
else:
new_dict[key] = 1
print(new_dict)
Use .replace() to remove the spaces. You can use defaultdict to make the code more concise:
from collections import defaultdict
string = input("Enter a string: ").lower().replace(" ", "")
new_dict = defaultdict(lambda: 0)
for key in string:
new_dict[key] += 1
I've been having issues with adding values to already existing key values.
Here's my code:
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
continue
else:
mydict[firstletter] = [word]
print(mydict)
assemble_dictionary('try.txt')
The try.txt contains a couple of words - Ability , Absolute, Butterfly, Cloud. So Ability and Absolute should be under the same key, however I can't find a function that would enable me to do so. Something similar to
mydict[n].append(word)
where n would be the line number.
Furthermore is there a way to easily locate the number of value in dictionary?
Current Output =
{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']}
but I want it to be
{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}
Option 1 :
you can put append statement when checking key is already exist in dict.
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
mydict[firstletter].append(word)
else:
mydict[firstletter] = [word]
print(mydict)
option 2 :
you can use dict setDefault to initialize the dict with default value in case key is not present then append the item.
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
mydict.setdefault(firstletter,[]).append(word)
print(mydict)
You could simply append your word to the existing key:
def assemble_dictionary(filename):
with open(filename,'r') as f:
for word in f:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
mydict[firstletter].append(word)
else:
mydict[firstletter] = [word]
Output:
{'a': ['ability', 'absolute'], 'b': ['butterfly'], 'c': ['cloud']}
Also (not related to the question) it's better to use the with statement to open your file, that will also close it once you're done working with it.
You can achieve it this way
mydict = {}
a = ['apple', 'abc', 'b', 'c']
for word in a:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
values = mydict[firstletter] # Get the origial values/words
values.append(word) # Append new word to the list of words
mydict[firstletter] = values
else:
mydict[firstletter] = [word]
print(mydict)
Outout :
{'a': ['apple', 'abc'], 'c': ['c'], 'b': ['b']}
mydict[firstletter] = [word], replaces the value
Since the key are in List format, try
mydict[firstletter].extend(word)
This question already has answers here:
Counting each letter's frequency in a string
(2 answers)
Closed 4 years ago.
How do I create a function that will let me input a word, and it will execute to create a dictionary that counts individual letters in the code. I would want it to display as a dictionary, for example, by inputting 'hello' it will display {'e': 1, 'h': 1, 'l': 2, 'o': 1}
I AM ALSO required to have 2 arguments in the function, one for the string and one for the dictionary. THIS IS DIFFERENT to the "Counting each letter's frequency in a string" question.
For example, I think I would have to start as,
d = {}
def count(text, d ={}):
count = 0
for l in text:
if l in d:
count +=1
else:
d.append(l)
return count
But this is incorrect? Also Would i need to set a default value to text, by writing text ="" in case the user does not actually enter any word?
Furthermore, if there were existing values already in the dictionary, I want it to add to that existing list. How would this be achieved?
Also if there were already existing words in the dictionary, then how would you add onto that list, e.g. dct = {'e': 1, 'h': 1, 'l': 2, 'o': 1} and now i run in terminal >>> count_letters('hello', dct) the result would be {'e': 2, 'h': 2, 'l': 4, 'o': 2}
If you can use Pandas, you can use value_counts():
import pandas as pd
word = "hello"
letters = [letter for letter in word]
pd.Series(letters).value_counts().to_dict()
Output:
{'e': 1, 'h': 1, 'l': 2, 'o': 1}
Otherwise, use dict and list comprehensions:
letter_ct = {letter:0 for letter in word}
for letter in word:
letter_ct[letter] += 1
letter_ct
You can use pythons defaultdict
from collections import defaultdict
def word_counter(word):
word_dict = defaultdict(int)
for letter in word:
word_dict[letter] += 1
return(word_dict)
print(word_counter('hello'))
Output:
defaultdict(<class 'int'>, {'h': 1, 'e': 1, 'l': 2, 'o': 1})
def count_freqs(string, dictionary={}):
for letter in string:
if letter not in dictionary:
dictionary[letter] = 1
else:
dictionary[letter] += 1
return dictionary
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict[letter] += 1
print word_dict
I want to create a new dictionary from a string, tracking the count of the letters from word. So what I'm trying to get is:
> word_dict = {'s':2, 't':1, 'a':1, 'c':1, 'k':1}
But I can't figure out how to do this. I get KeyError with my current code
Use the collections.Counter() class instead:
from collections import Counter
word_dict = Counter(word)
The Counter does the exact same thing; count occurrences of each letter in word.
In your specific case you didn't first check if the key already exists or provide a default if it doesn't. You could use dict.get() to do that:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict[letter] = word_dict.get(letter, 0) + 1
print word_dict
or use dict.setdefault() separately to explicitly set a default before incrementing:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict.setdefault(letter, 0)
word_dict[letter] += 1
print word_dict
or test for the key yourself:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
if letter not in word_dict:
word_dict[letter] = 0
word_dict[letter] += 1
print word_dict
in decreasing order of efficiency.
Or you could use a collections.defaultdict() object to automatically insert a 0 if there the key doesn't yet exist:
from collections import defaultdict
word_dict = defaultdict(int)
for letter in word:
word_dict[letter] += 1
print word_dict
This is essentially what the Counter class does, but the type adds some other niceties such as listing the most common keys or combining counters.
Demo:
>>> from collections import defaultdict, Counter
>>> word = 'stacks'
>>> word_dict = {} # to form new dictionary formed from
>>> for letter in word:
... word_dict[letter] = word_dict.get(letter, 0) + 1
...
>>> word_dict
{'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1}
>>> word_dict = defaultdict(int)
>>> for letter in word:
... word_dict[letter] += 1
...
>>> word_dict
defaultdict(<type 'int'>, {'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1})
>>> Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})
Try this
from collections import Counter
>>>Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})
I have started on a program to count vowels and have seemed to be getting nowhere. I need to count vowels from a string and then display the vowels. I need to do this by storing the number of occurrences in variables. Like this :
a = 0
b = 0
....
then print the lowest.
Current code (its not that much ):
string = str(input("please input a string: "))
edit= ''.join(string)
print(edit)
I have tried a number of methods just by my self and don't seem to get anywhere.
You could use a dictionary comprehension:
>>> example = 'this is an example string'
>>> vowel_counts = {c: example.count(c) for c in 'aeoiu'}
>>> vowel_counts
{'i': 2, 'o': 0, 'e': 5, 'u': 0, 'a': 2}
Then finding the minimum, maximum etc. is trivial.
>>> a="hello how are you"
>>> vowel_count = dict.fromkeys('aeiou',0)
>>> vowel_count
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}
>>> for x in 'aeiou':
... vowel_count[x]=a.count(x)
...
>>> vowel_count
{'a': 1, 'i': 0, 'e': 2, 'u': 1, 'o': 3}
now from here you can print low nd max
You can use dictionary for this problem. Iterate over each character and if the character is a vowel, put it in dictionary with count 0 and increment its count by 1, and for every next occurrence keep incrementing the count.
>>> string = str(input("please input a string: "))
please input a string: 'Hello how are you'
>>> dt={} # initialize dictionary
>>> for i in string: # iterate over each character
... if i in ['a','e','i','o','u']: # if vowel
... dt.setdefault(i,0) # at first occurrence set count to 0
... dt[i]+=1 # increment count by 1
...
>>> dt
{'a': 1, 'u': 1, 'e': 2, 'o': 3}
word = input('Enter Your word : ')
vowel = 'aeiou'
vowel_counter = {}
for char in word:
if char in vowel:
vowel_counter[char] = vowel_counter.setdefault(char,0)+1
sorted_result = sorted(vowel_counter.items(), reverse=True,key=lambda x : x[1])
for key,val in sorted_result:
print(key,val)