I'm attempting to try a simple command on the command line,
dict(zip(ascii_lowercase, range(4)))
expecting to get
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
but I keep getting the error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ascii_lowercase' is not defined
What am I missing here?
ascii_lowercase is a value provided by the string module. To use it unqualified, you must have previously imported it via:
from string import ascii_lowercase
Why zip with range when you can enumerate?
from string import ascii_lowercase
print {b:a for a,b in enumerate(ascii_lowercase[:4])}
Output:
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
You can also import the string module, and apply your own function using string.ascii_lowercase:
Test
import string
print(dict(zip(string.ascii_lowercase, range(4))))
Output
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Related
So i have this code that is supposed to count the characters in a user inputted sentece
import pprint
message = str(input())
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
however the problem is, it gives an output for every successive character i.e if you give a sentence with 3 characters in it e.g "the" it will give 3 outputs
the
{'t': 1}
{'h': 1, 't': 1}
{'e': 1, 'h': 1, 't': 1}
Process finished with exit code 0
how do i get it only to give the final output with all characters counted? thanks
You're getting multiple outputs because the print (pprint.pprint) is in a for loop.
Just remove the indentation from the pprint.pprint(count) line, so that it isn't in the for loop:
import pprint
message = str(input())
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
You print the output every line so this is expected. You can achieve the same with much simpler code using Counter -
from collections import Counter
import pprint
message = str(input())
count = Counter(message)
pprint.pprint(dict(count))
import pprint
message = str(input())
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
you just have to take off pprint.pprint(count) from for cycle
import pprint
message = str(input())
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
output:
messaggio
{'a': 1, 'e': 1, 'g': 2, 'i': 1, 'm': 1, 'o': 1, 's': 2}
If I understood your objective correctly; this might work. if character.isalpha() filters non alphabetic characters in the string like !"#$%&'()*+,-./:;<=>?#[\]^_{|}~` and white spaces only take into account the alphabetic letters.
from pprint import pprint
message = 'This is a test string to check whether character to occurences mapping works correctly' #str(input())
occurrences_dict = {}
for character in message:
if character.isalpha() and character not in occurrences_dict:
occurrences_dict[character] = message.count(character)
pprint(occurrences_dict)
{'T': 1,
'a': 4,
'c': 9,
'e': 8,
'g': 2,
'h': 5,
'i': 4,
'k': 2,
'l': 1,
'm': 1,
'n': 3,
'o': 5,
'p': 2,
'r': 8,
's': 6,
't': 8,
'u': 1,
'w': 2,
'y': 1}
I would like to create some basic statistics for several lists of data and store them in a dictionary:
>>> from statistics import mean,median
>>> a,b,c=[1,2,3],[4,5,6],[7,8,9]
The following list comprehension works and outputs stats for "a":
>>> [eval("{}({})".format(op,a)) for op in ['mean','median','min','max']]
[2, 2, 1, 3]
Assigning the list's variable name (a) to another object (dta) and evaluating "dta" in a list comprehension also works:
>>> dta="a"
>>> [eval("{}({})".format(op,eval("dta"))) for op in ['mean','median','min','max']]
[2, 2, 1, 3]
But when I try to tie this all together in a dictionary comprehension, it does not work:
>>> {k:[eval("{}({})".format(op,eval("k"))) for op in ['mean','median','min','max']] for k in ['a','b','c']}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
File "<stdin>", line 1, in <listcomp>
File "<string>", line 1, in <module>
NameError: name 'k' is not defined
My guess is that the eval is processed before the comprehension, which is why 'k' is not yet defined? Any suggestions for how to get this work or a different routine that would accomplish the same output?
Do not quote the k in the inner eval:
{k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b','c']}
^
Or drop eval altogether:
[[mean(k), median(k), min(k), max(k)] for k in [a, b, c]]
You can do a simple workaround with the keys to change this to a dictionary comprehension.
Try removing the quotation marks around k in your call to eval in the format function.
I ran the following commands:
> from statistics import mean,median
> a,b,c=[1,2,3],[4,5,6],[7,8,9]
> {k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b','c']}
and got the following output:
{'a': [2.0, 2, 1, 3], 'c': [8.0, 8, 7, 9], 'b': [5.0, 5, 4, 6]}
I have a Python script that prints out a randomly generated password, then prints prints it to a text file, adding a new row every time it is called. For example:
PSWD = (str(pswd01)) + (str(pswd02)) + (str(pswd03)) + (str(pswd04))
# Note, variables pswd01, pswd02 etc are randomly created earier in the script.
print(PSWD)
with open('PSWD_output.txt','a') as f:
f.write(PSWD + '\n')
f.close()
Note, the variable PSWD contains lower case, upper case, and numbers.
I then want to read the file and count the number of individual characters, and print a report to a different text file, but not sure how I can do this. I have asked a similar question here, which answers how to print a character report to the console.
Any idea how I can read PSWD_output.txt, and count each different character, writing the result to a separate text file?
Any help appreciated!
Use dictionaries to count characters repeat as below:
my_dictionary = {}
f = open('PSWD_output.txt','r')
line = f.readline()
while(line):
for letter in line:
if letter in my_dictionary:
my_dictionary[letter] +=1
else:
my_dictionary[letter] = 1
line = f.readline()
print my_dictionary
For a text file containing:
salam
asjf
asjg;
asdkj
14kj'asdf
5
returns:
>>> ================================ RESTART ================================
>>>
{'a': 6, 'j': 4, 'd': 2, 'g': 1, 'f': 2, 'k': 2, '\n': 6, 'm': 1, 'l': 1, "'": 1, '1': 1, 's': 5, '5': 1, '4': 1, ';': 1}
>>>
You can use a Counter. It takes an iterable (and strings are iterable: iterate over the characters) and stores the result as a dictionary
>>> from collections import Counter
>>> c = Counter("foobarbaz")
>>> c
Counter({'o': 2, 'a': 2, 'b': 2, 'z': 1, 'f': 1, 'r': 1})
>>> c.most_common(2)
[('o', 2), ('a', 2)]
In the following code, I would like to know if the grade_to_score dictionary will be created every time the method is called?
def get_score(grade):
grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0} # step 1
return grade_to_score.get(grade, -1)
also, what is the way to confirm that? I am working with Python 2.7
Yes it will. To get around it, you can pass it as a default argument so that it will only be evaluated once:
def get_score(grade, grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0}):
return grade_to_score.get(grade, -1)
or the better approach:
def get_score(grade, grade_to_score = None):
if grade_to_score == None:
grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0}
return grade_to_score.get(grade, -1)
To answer your question "what is the way to confirm that?", you can check whether the same object is being used each time:
def get_score(grade):
grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0} # step 1
print(id(grade_to_score)) # check object ID
return grade_to_score.get(grade, -1)
Now you can call it:
>>> a = get_score("")
50252080
>>> b = get_score("")
50249920
>>> c = get_score("")
50249776
A different id means a different object, so grade_to_score clearly is being created anew on each call. Interestingly, this doesn't happen if you call in a for loop:
>>> for _ in range(3):
a = get_score("")
50249920
50249920
50249920
>>> scores = [get_score(grade) for grade in "ABC"]
53737032
53737032
53737032
Yes, the dictionary is created a-new every time the function is called.
You can make it a global instead, or make it a function default:
grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0} # step 1
def get_score(grade):
return grade_to_score.get(grade, -1)
or
def get_score(grade, grade_to_score={'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0}):
return grade_to_score.get(grade, -1)
In the second casegrade_to_score is passed into the function as a local, so lookups are (marginally) faster.
In both cases the dictionary literal is executed once, on module import. Note that in both cases, because grade_to_score is a mutable dictionary, so any changes you make to it are global, not local to the get_score() call.
Given the string:
a='dqdwqfwqfggqwq'
How do I get the number of occurrences of each character?
In 2.7 and 3.1 there's a tool called Counter:
>>> import collections
>>> results = collections.Counter("dqdwqfwqfggqwq")
>>> results
Counter({'q': 5, 'w': 3, 'g': 2, 'd': 2, 'f': 2})
Docs. As pointed out in the comments it is not compatible with 2.6 or lower, but it's backported.
Not highly efficient, but it is one-line...
In [24]: a='dqdwqfwqfggqwq'
In [25]: dict((letter,a.count(letter)) for letter in set(a))
Out[25]: {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
You can do this:
listOfCharac={}
for s in a:
if s in listOfCharac.keys():
listOfCharac[s]+=1
else:
listOfCharac[s]=1
print (listOfCharac)
Output {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
This method is efficient as well and is tested for python3.
For each letter count the difference between string with that letter and without it, that way you can get it's number of occurences
a="fjfdsjmvcxklfmds3232dsfdsm"
dict(map(lambda letter:(letter,len(a)-len(a.replace(letter,''))),a))
lettercounts = {}
for letter in a:
lettercounts[letter] = lettercounts.get(letter,0)+1
python code to check the occurrences of each character in the string:
word = input("enter any string = ")
for x in set(word):
word.count(x)
print(x,'= is', word.count(x))
Please try this code if any issue or improvements please comments.
one line code for finding occurrence of each character in string.
for i in set(a):print('%s count is %d'%(i,a.count(i)))