This question already has an answer here:
Create dictionary comprehension from list with condition syntax
(1 answer)
Closed 4 years ago.
I need to create a multiset tracking the frequencies of characters appearing in a given string. I wanted to implement this using dict comprehensions, but what I tried:
mySet = {letter : mySet.get(letter, 0) + 1 for letter in myStr}
Did not seem to work... as mySet.get(letter, 0) always seems to return 0. Is there another way to accomplish this simple task without resorting to loops?
Try Counter
from collections import Counter
Counter('Hello World')
This returns
Counter({' ': 1, 'H': 1, 'W': 1, 'd': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1})
Related
This question already has answers here:
Does Python have an ordered set?
(15 answers)
Closed 3 years ago.
Is there a way of ordering a set in base python?
For example:
A = {1, 2, 3}
B = {3, -6, 2, 0}
print union(A, B)
Expected Output:
({-6, 0, 1, 2, 3}, 5)
My attempt:
x = A | B
y = len(x)
print((set(x), y))
My output:
({0, 1, 2, 3, -6}, 5)
I have read some of the answers for other questions and there are ways of doing it with various packages, but for this exercise, I am NOT meant to import any packages, just doing it in base python (if that is what it is called) if possible.
No, sets are unordered by definition and implementation. To create a sorted list, convert your set to a list and sort it:
List = sorted(your_set)
This question already has answers here:
How can I get list of values from dict?
(7 answers)
Closed 5 years ago.
I want to extract the values from a dictionary and print them as a list. For example: If i have
letter = {"i": 3, "o": 2, "u": 2}
and want to extract 3,2, and 2 and print it as a list
[3, 2, 2]
How do I do this?
I've tried
print([x[::] for x in letter])
However, this prints out ['i', 'o', 'u'] and not [3, 2, 2].
Thank you for the help in advanced :)
There is a method in Python called .keys() that allows you to get the keys from a dict. Similarly, there is also a method called values() for the converse.
These are dict instance methods, ie:
myDict = { "i": 0, "t": 1, "f": 2 }
print(myDict.values())
You can just call dict.values()
Further details here
Try letter.values(), which gives you dict_values([3, 2, 2])
>>> letter = {"i": 3, "o": 2, "u": 2}
>>> print(list(letter.values()))
[3, 2, 2]
This question already has answers here:
Order of keys in dictionary
(3 answers)
Closed 7 years ago.
I have two lists which I'm mapping into a dictionary.
The two lists are-
a = ['a','b','c','d'] and b = [1,2,3,4] .
When I run the command
>>> d = dict(zip(a,b))
>>> d
I get
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
whereas the expected value is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Why this change in the order of the keys?
There is no inherent "obvious" order in the keys of a dict. Admittedly, the docs only spell it out for CPython, but also note
If items(), keys(), values(), iteritems(), iterkeys(), and
itervalues() are called with no intervening modifications to the
dictionary, the lists will directly correspond.
which says by omission that otherwise they might change.
(Note that there is an order, but it involves the hashes of the keys, so it's not as easy as "a before b", and in particular, since a few years back, it is liable to change with each new call of the executable.)
There is no order in a dictionary.
{'a': 1, 'b': 2, 'c': 3, 'd': 4} == {'a': 1, 'c': 3, 'b': 2, 'd': 4}
This question already has answers here:
How do you convert a stringed dictionary to a Python dictionary? [duplicate]
(3 answers)
Closed 8 years ago.
I got a string, it's like:
"{'a': 1, 'b': 2, 'c': 3}"
I want to assign a variable to this string and make the variable a dict.
It sounds easy, but I spend half hour and didn't figure it out. How to do it?
Use the ast.literal_eval() function as follows:
>>> import ast
>>> ast.literal_eval("{'a': 1, 'b': 2, 'c': 3}")
{'a': 1, 'b': 2, 'c': 3}
You could use it in a programme as follows:
import ast
dictString = "{'a': 1, 'b': 2, 'c': 3}";
dictFinal = ast.literal_eval(dictString)
print (dictFinal)
There is more help in the docs at this link
I have many Python lists filled with words and among those words I would like to keep the ones who appears in at least two lists.
My first guess was to collapse all those list into a big one and then to keep the words who have a count > 1.
The problem is that I have some memory issue when I try to collapse all the list into a big one.
Any help please ? thanks a lot
If you're counting things, use a counter!
from collections import Counter
c = Counter(['bob','steve','steve','joe'])
# c == Counter({'steve': 2, 'bob': 1, 'joe': 1})
c.update(['alan','jose','steve'])
# c == Counter({'steve': 3, 'jose': 1, 'bob': 1, 'joe': 1, 'alan': 1})