Python Forum
get method not counting number of strings in dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: get method not counting number of strings in dictionary (/thread-27621.html)



get method not counting number of strings in dictionary - LearningTocode - Jun-13-2020

Hi,

I've only been learning to code for a couple of weeks now. This is my first post. If I've posted incorrectly please do let me know.

So, I'vebeen typing this code:

counts = dict()
names = {"x", "y", "z", "x", "a"}
for name in names:
    counts[name] = counts.get(name, 0) + 1
print(counts)
and when running it, I'm getting this output:
Output:
D:\Python\helloworld\venv\Scripts\python.exe D:/Python/helloworld/app.py {'a': 1, 'z': 1, 'x': 1, 'y': 1} Process finished with exit code 0
Why isn't the code correctly counting the number of values in the "names" variable?

Thank you


RE: get method not counting number of strings in dictionary - deanhystad - Jun-13-2020

You need to wrap you code in python tags, otherwise the indentation is lost.

You create a set named "names" that contains "x", "Y", "Z" and "a". You probably think "names" has two "x"'s because there are two "x"'s in the initializer, but one of the main things that differentiates a set from a list or tuple is it only holds one of each value.

Or did you think "names" was a dictionary because you used the curly brackets? Both sets and dictionaries use {}. The difference between a set and dictionary is the dictionary initializer contains key value pairs separated by ":".

So the answer to your question is "counts" shows only one count for each name because each name only appears once. Replace you curly brackets with square brackes [] to make names a list, and count["x"] will be 2.


RE: get method not counting number of strings in dictionary - LearningTocode - Jun-13-2020

(Jun-13-2020, 11:03 PM)deanhystad Wrote: You need to wrap you code in python tags, otherwise the indentation is lost.

You create a set named "names" that contains "x", "Y", "Z" and "a". You probably think "names" has two "x"'s because there are two "x"'s in the initializer, but one of the main things that differentiates a set from a list or tuple is it only holds one of each value.

Or did you think "names" was a dictionary because you used the curly brackets? Both sets and dictionaries use {}. The difference between a set and dictionary is the dictionary initializer contains key value pairs separated by ":".

So the answer to your question is "counts" shows only one count for each name because each name only appears once. Replace you curly brackets with square brackes [] to make names a list, and count["x"] will be 2.

Thank you! Smile
I'm still becoming familiar with the vocabulary.. but yet replacing the {} with [] worked!