Sort value in dictionary by value in Python - python

I have something like this in Python to count the frequency of characters in a text, but i can't sort the values on the dictionary "v".
abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
count = 0
for char in text:
if c == char:
count = count +1
v[c] = count
sorted(v.items(), key=lambda x:x[1])
print v
I try to search here on stackoverflow but never solve my problem, the aspect of the output is this:
{'a': 2, 'b': 4, 'e': 4, 'd': 36, 'g': 31, 'f': 37, 'i': 14, 'h': 4, 'k': 51, 'j': 31, 'l': 34, 'n': 18, 'q': 13, 'p': 2, 'r': 9, 'u': 1, 't': 1, 'w': 36, 'v': 15, 'y': 14, 'x': 8, 'z': 10}
I want sort by value, so it's different from other posts.

If you just want to print them in order, just print the output of sorted:
abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
count = 0
for char in text:
if c == char:
count = count +1
v[c] = count
print sorted(v.items(), key=lambda x:x[1])
For text = "helloworld" you get:
[('e', 1), ('d', 1), ('h', 1), ('r', 1), ('w', 1), ('o', 2), ('l', 3)]

A python dictionary is an unordered collection of items. Therefore, it can't be sorted.
Try looking into OrderedDict from collections.

you can use Counter
from collections import Counter
text = "I have something like this in Python to count the frequency of characters in a text, but i can't sort the values on the dictionary"
print(Counter(text))
output:
Counter({' ': 24, 't': 15, 'e': 11, 'n': 9, 'h': 8, 'i': 8, 'o': 8, 'a': 7, 'c': 6, 's': 5, 'r': 5, 'u': 4, 'y': 3, 'f': 2, 'l': 2, 'v': 2, "'": 1, 'q': 1, 'd': 1, 'I': 1, 'm': 1, 'g': 1, 'b': 1, 'x': 1, ',': 1, 'P': 1, 'k': 1})

Related

Map Lowercase Alphabet to Integers [duplicate]

This question already has answers here:
creating dict where keys are alphabet letters and values are 1-26 using dict comprehension
(9 answers)
Closed 2 months ago.
i cant make a dict where to every one letter will be a value in the n + 1 format, start from 1.
this is my code:
dict1 = {x: y for x in 'abcdefghijklmnopqrstunvwxyz' for y in range(1, 20, 1)}
print(dict1)
i get it:
{'a': 19, 'b': 19, 'c': 19, 'd': 19, 'e': 19, 'f': 19, 'g': 19, 'h': 19, 'i': 19, 'j': 19, 'k': 19, 'l': 19, 'm': 19, 'n': 19, 'o': 19, 'p': 19, 'q': 19, 'r': 19, 's': 19, 't': 19, 'u': 19, 'v': 19, 'w': 19, 'y': 19, 'z': 19}
can u tell me why and how to get it: {'a': 1, 'b':2...
Use the tools provided by Python to make this easier to implement and read. First, don't hardcode the lowercase alphabet, use the stdlib string. Next, don't do the arithmetic yourself, it's easy to get wrong: there are 26 letters but range(1, 20, 1) generates only 19 digits. You also have a typo in your alphabet (I assume): tunvw. Lastly, use enumerate() which generates tuples consisting of an element of a sequence and an auto-incrementing integer, and use the start keyword argument to set the starting integer value.
import string
d = {x: y for x, y in enumerate(string.ascii_lowercase, start=1)}
Your code doesn't produce the result you want because for each integer from 1 to 19, it assigns the integer to the value for each key ('a', 'b', 'c', etc.). The first iteration of the outer for produces the dictionary {'a': 1, 'b': 2, 'c': 3, etc.}. Then, each subsequent iteration of the outer for overwrites these values with the new integer: 2, 3, 4, etc.
This is easy to see if we convert the comprehension to loops:
d = {}
for y in range(1, 20, 1):
for x in 'abcdefghijklmnopqrstuvwxyz':
d[x] = y
print(d)
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1, 'i': 1, 'j': 1, 'k': 1, 'l': 1, 'm': 1, 'n': 1, 'o': 1, 'p': 1, 'q': 1, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 1, 'w': 1, 'x': 1, 'y': 1, 'z': 1}
{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2, 'f': 2, 'g': 2, 'h': 2, 'i': 2, 'j': 2, 'k': 2, 'l': 2, 'm': 2, 'n': 2, 'o': 2, 'p': 2, 'q': 2, 'r': 2, 's': 2, 't': 2, 'u': 2, 'v': 2, 'w': 2, 'x': 2, 'y': 2, 'z': 2}
{'a': 3, 'b': 3, 'c': 3, 'd': 3, 'e': 3, 'f': 3, 'g': 3, 'h': 3, 'i': 3, 'j': 3, 'k': 3, 'l': 3, 'm': 3, 'n': 3, 'o': 3, 'p': 3, 'q': 3, 'r': 3, 's': 3, 't': 3, 'u': 3, 'v': 3, 'w': 3, 'x': 3, 'y': 3, 'z': 3}
...
{'a': 19, 'b': 19, 'c': 19, 'd': 19, 'e': 19, 'f': 19, 'g': 19, 'h': 19, 'i': 19, 'j': 19, 'k': 19, 'l': 19, 'm': 19, 'n': 19, 'o': 19, 'p': 19, 'q': 19, 'r': 19, 's': 19, 't': 19, 'u': 19, 'v': 19, 'w': 19, 'x': 19, 'y': 19, 'z': 19}
edit: You don't need a comprehension to do this. There is another, pretty clean solution:
import string
d = dict(enumerate(string.ascii_lowercase, start=1))
This solution relies on the dict(iterable) constructor:
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
Try to zip the alphabet and the range to see what you get like that:
z1 = zip('abcdefghijklmnopqrstunvwxyz', range(1, 28, 1))
Which will give us:
for tup in z1:
print(tup)
Output:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
('e', 5)
('f', 6)
('g', 7)
('h', 8)
('i', 9)
('j', 10)
('k', 11)
('l', 12)
('m', 13)
('n', 14)
('o', 15)
('p', 16)
('q', 17)
('r', 18)
('s', 19)
('t', 20)
('u', 21)
('n', 22)
('v', 23)
('w', 24)
('x', 25)
('y', 26)
('z', 27)
Now you can assign each element of each tuple to x, y:
d1 = {x, y for x, y in zip('abcdefghijklmnopqrstunvwxyz', range(1, 28, 1))}
Output:
print(d1)
{'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9,
'j': 10,
'k': 11,
'l': 12,
'm': 13,
'n': 22,
'o': 15,
'p': 16,
'q': 17,
'r': 18,
's': 19,
't': 20,
'u': 21,
'v': 23,
'w': 24,
'x': 25,
'y': 26,
'z': 27}

How do I get the points of each word?

I'm making a program that could count the points of two or more words. How do I get the value of each point in a list in an array? I already have a dictionary of points.
points_dictionary = {
'A': 1, 'B': 3, 'C': 3,
'D': 2, 'E': 1, 'F': 4, 'G': 2,
'H': 4, 'I': 1, 'J': 8, 'K': 5,
'L': 1, 'M': 3, 'N': 1, 'O': 1,
'P': 3, 'Q': 10, 'R': 1, 'S': 1,
'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8,
'Y': 4, 'Z': 10, '#': 0, '0':3
}
I have a list that looks like thiscurrwords = ['PEARS' 'MANGO' 'ORANGE]
I have made a code that can get the points of each letter but its output adds all the points.
for you in currwords:
for yeah in you:
trans = list(yeah)
trans = points_dictionary[yeah[0]]
total_words.append(trans)
final1 = sum(total_words)
print(final1)
Every time I use this code it only outputs the total points on what is on the list. How do I get the points specifically on each word like PEAR = 6 MANGO = 8 and ORANGE = 7
You could use sum together with map:
points_dictionary = {
'A': 1, 'B': 3, 'C': 3,
'D': 2, 'E': 1, 'F': 4, 'G': 2,
'H': 4, 'I': 1, 'J': 8, 'K': 5,
'L': 1, 'M': 3, 'N': 1, 'O': 1,
'P': 3, 'Q': 10, 'R': 1, 'S': 1,
'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8,
'Y': 4, 'Z': 10, '#': 0, '0':3
}
currwords = ['PEARS', 'MANGO', 'ORANGE']
for word in currwords:
print(word, sum(map(lambda c: points_dictionary.get(c, 0), word)))
Output
PEARS 7
MANGO 8
ORANGE 7
As an alternative you could use a generator expression:
for word in currwords:
print(word, sum(points_dictionary.get(c, 0) for c in word))
The idea of both map and the generator expression is to map the letters of each word to the corresponding point values.
Let's do it the old school way:
points_dictionary = {
'A': 1, 'B': 3, 'C': 3,
'D': 2, 'E': 1, 'F': 4, 'G': 2,
'H': 4, 'I': 1, 'J': 8, 'K': 5,
'L': 1, 'M': 3, 'N': 1, 'O': 1,
'P': 3, 'Q': 10, 'R': 1, 'S': 1,
'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8,
'Y': 4, 'Z': 10, '#': 0, '0':3
}
currwords = ['PEARS', 'MANGO', 'ORANGE']
sumsOfwords = []
sum = 0
i = -1
for words in currwords:
for word in words:
if words == currwords[i + 1]:
sum = sum + points_dictionary[word]
else:
sumsOfwords.append(sum)
sum = 0
sum = sum + points_dictionary[word]
i = i + 1
sumsOfwords.append(sum)
print(sumsOfwords)
OUTPUT:
[7, 8, 7]
dictionary = dict(zip(currwords, sumsOfwords))
print(dictionary)
OUTPUT:
{'PEARS': 7, 'MANGO': 8, 'ORANGE': 7}
I think the issue here is that you append trans to total_words at each iteration, but never reset its value. You could add a
total_words = []
inside of the first loop. Also, inside of your for yeah in you loop, you define trans twice, so the first one is never used. After correcting that, your code should look like this :
for you in currwords:
total_words = []
for yeah in you:
trans = points_dictionary[yeah]
total_words.append(trans)
final1 = sum(total_words)
print(final1)

Adding value depending on dictionary value

Say I have a dictionary like this,
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
Now, say I have a variable like this.
letter = 'i'
I want to add the corresponding value to the variable score. So since letter is equal to i, then score should equal 1
SCRABBLE_LETTER_VALUES = {'a': 1, 'c': 3, 'b': 3, 'e': 1, 'd': 2, 'g': 2, 'f': 4, 'i': 1, 'h': 4, 'k': 5, 'j': 8, 'm': 3, 'l': 1, 'o': 1, 'n': 1, 'q': 10, 'p': 3, 's': 1, 'r': 1, 'u': 1, 't': 1, 'w': 4, 'v': 4, 'y': 4, 'x': 8, 'z': 10}
>>> SCRABBLE_LETTER_VALUES['i']
1
>>> SCRABBLE_LETTER_VALUES['z']
10
Dictionary values are accessed using dictionary_name[key]. So in this case:
score+=SCRABBLE_LETTER_VALUES[letter]
You also need to assign score to something before you do this:
score=0
You might find it useful to read the documentation on dictionaries: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Firstly you need to know how python plays with dictionary- the question you asked in very simple thus people are downvoting!
Answering you question:
You have the following code in mind and struggling for the rest. I will be answering them accordingly under your statements.
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
letter = 'i'
In python to get value for a corresponding key it work like dictionary[key], which gives the output.
So for your problem if we do SCRABBLE_LETTER_VALUES[letter], its the same as doing SCRABBLE_LETTER_VALUES['i'] where 'i' is the key and we will get 1 as output.
Hence for SCRABBLE_LETTER_VALUES[letter] we get 1 as output!
I want to add the corresponding value to the variable score. So since letter is equal to i
Assigning the corresponding value to the variable score is score = SCRABBLE_LETTER_VALUES[letter]
then score should equal 1
and we know now for sure that the value of score is 1. Don't we?
For SCRABBLE_LETTER_VALUES[letter] value is 1 when letter= 'i' thus score is 1

Creating a Python dictionary using a comprehension

I am trying to create a python dictionary with the following values in python 2.7.3:
'A':1
'B':2
'C':3
.
.
.
.
'Z':26
using either of the following lines:
theDict = {x:y for x in map(chr,range(65,91)) for y in range(1,27)}
or
theDict = {x:y for x in map(chr,range(65,91)) for y in list(range(1,27))}
In both cases, I get the following result:
'A':26
'B':26
'C':26
.
.
.
.
'Z':26
I don't understand why the second for is not generating the numbers 1-26. Maybe it is, but if so, I don't understand why I am only getting 26 for the value of each key. If I don't create a dictionary (i.e. change x:y with just x or y), x = capital letters and y = 1-26.
Can someone explain what I am doing wrong and suggest a possible approach to get the result that I want.
Why it's wrong: Your list comprehension is nested. It's effectively something like this:
d = {}
for x in map(chr, range(65, 91)):
for y in range(1,27):
d[x] = y
As you can see, this isn't what you want. What it does is set y to 1, then walk through the alphabet, setting all letters to 1 i.e. {'A':1, 'B':1, 'C':1, ...}. Then it does it again for 2,3,4, all the way to 26. Since it's a dict, later settings overwrite earlier settings, and you see your result.
There are several options here, but in general, the solution to iterate over multiple companion lists is a pattern more like this:
[some_expr(a,b,c) for a,b,c in zip((a,list,of,values), (b, list, of, values), (c, list, of values))]
The zip pulls one value from each of the sublists and makes it into a tuple for each iteration. In other words, it converts 3 lists of 4 items each, into 4 lists of 3 items each (in the above). In your example, you have 2 lists of 26 items, when you want 26 pairs; zip will do that for you.
Try:
>>> {chr(k):k-64 for k in range(65,91)}
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}
Or, if you want to do what you are doing use zip:
>>> {x:y for x,y in zip(map(chr,range(65,91)),range(1,27))}
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}
The reason yours is not working, is that your comprehension is executing the inner the outer loop times. ie, try this in the shell:
>>> [(chr(outter), inner) for outter in range(65,91) for inner in range(1,27)]
[('A', 1), ('A', 2), ('A', 3), ('A', 4),... ('A', 26),
...
...
('Z', 1), ('Z', 2), ('Z', 3), ('Z', 4), ..., ('Z', 26)]
So if you do:
>>> len([(chr(outter), inner) for outter in range(65,91) for inner in range(1,27)])
676
You can see that it is executing 26x26 times (26x26=676)
Since a dict will just update with the new value, the last value for each letter is used:
>>> dict([(chr(outter), inner) for outter in range(65,91) for inner in range(1,27)])
{'A': 26, 'C': 26, 'B': 26, 'E': 26, 'D': 26, 'G': 26, 'F': 26, 'I': 26, 'H': 26, 'K': 26, 'J': 26, 'M': 26, 'L': 26, 'O': 26, 'N': 26, 'Q': 26, 'P': 26, 'S': 26, 'R': 26, 'U': 26, 'T': 26, 'W': 26, 'V': 26, 'Y': 26, 'X': 26, 'Z': 26}
Which shows why you are getting what you are getting.
You can try the following:
theDict = {chr(y):y - 64 for y in range(65, 91)}
print theDict
Output:
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}

How to sum items in a for loop in python?

I have the following code:
dict = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1,
'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
word = 'banana'
for letter in word:
print dict[letter]
I get the following output
3
1
1
1
1
How can I add these values?
That is how can I print the output as 8
You can use sum and a generator expression:
>>> # Please don't name a variable `dict` -- it overshadows the built-in
>>> dct = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }
>>> word = 'banana'
>>> print sum(dct[letter] for letter in word)
8
>>>
Note that the above solution assumes that all of the characters in word can be found in dct. If this isn't always the case, then you can use dict.get to avoid a KeyError:
>>> dct = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }
>>> word = '$banana1'
>>> print sum(dct.get(letter, 0) for letter in word)
8
>>>
Here is another way that you can sum the items in the list.
dict = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1,
'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
word = 'banana'
sum = 0
for letter in word:
sum+=dict[letter]
print sum

Categories

Resources