In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value

import collections
word_count = collections.defaultdict(int)
for word in ["foo", "bar", "foo", "foobar"]:
    word_count[word] += 1
print word_count
# >>> defaultdict(<type 'int'>, {'foobar': 1, 'foo': 2, 'bar': 1})

If you don't know what key is given to the dictionary type, it is often the case that if the key does not exist, it is initialized with foo, and collections.defaultdict fills it. If you do defaultdict (int), it will be initialized to 0 at the first access like ↑, but what does this mean after all?

import collections
word_count = {}
for word in ["foo", "bar", "foo", "foobar"]:
    if not word in word_count:
        word_count[word] = int()
    word_count[word] += 1
print word_count

The process is the same as this. After all, it's fine if it is a function with no arguments and returns some value. So it's pretty easy to understand if you use lambda and do something like defaultdict (lambda: []). ** Addendum: In the example of generating this empty list, it is easier to read if you pass list () without using lambda. A slightly more complicated example below where you should use lambda. ** **

If you develop the previous example, you can count the frequency of appearance of each alphabet.

import collections
word_count = collections.defaultdict(lambda: [0 for i in range(26)])
for word in ["foo", "bar", "foo", "foobar"]:
    for chara in word:
        word_count[word][ord(chara)-ord("a")] += 1
print word_count
# >defaultdict(<function <lambda> at 0x10e5147d0>, {'foobar': [1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 'foo': [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'bar': [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]})

defaultdict () itself also returns defaultdict, so you can of course defaultdict (defaultdict (lambda: {"name ":" null "," age ": 20})).

Recommended Posts

In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
Get the value of a specific key in a list from the dictionary type in the list with Python
Delete a particular character in Python if it is the last
Check if the string is a number in python
A memo when checking whether the specified key exists in the defined dictionary with python
I want to initialize if the value is empty (python)
[python] How to check if the Key exists in the dictionary
Get the value of a specific key up to the specified index in the dictionary list in Python
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
[Python] Execution time when a function is entered in a dictionary value
How to create a heatmap with an arbitrary domain in Python
A simple reason why the return value of round (2.675,2) is 2.67 in python (it should be 2.68 in reality ...)
Hash in Perl is a dictionary in Python
What is the fastest way to create a reverse dictionary in python?
[Python] Get the files in a folder with Python
Sort dict in dict (dictionary in dictionary) with a specific key
Isn't there a default value in the dictionary?
If you guys in the scope kitchen can do it with a margin ~ ♪
[Python Data Frame] When the value is empty, fill it with the value of another column.
How to use any or all to check if it is in a dictionary (Hash)
Check if it is Unix in the scripting language
Determine if an attribute is defined in the object
How to check in Python if one of the elements of a list is in another list
Check if it is Unix in the scripting language
It is easy to execute SQL with Python and output the result in Excel
How to find out if there is an arbitrary value in "somewhere" of pandas DataFrame
Recursively get the Excel list in a specific folder with python and write it to Excel.
When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?
How to check if the contents of the dictionary are the same in Python by hash value
Solution if the module is installed in Python but you get an error in Jupyter notebook
An easy way to view the time taken in Python and a smarter way to improve it
Determine if a string is a time with a python regular expression
How to convert an array to a dictionary with Python [Application]
How to check if a value exists in an enum
How to get the last (last) value in a list in Python
Create a dictionary in Python
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
How is the progress? Let's get on with the boom ?? in Python
Python will fail if there is a space after the backslash
Play a sound in Python assuming that the keyboard is a piano keyboard
Check if the configuration file is read in an easy-to-understand manner
How to judge that the cross key is input in Python3
How to check the memory size of a dictionary in Python
[Python] The value written in Openpyxl is displayed in exponential notation (E).
Read a file in Python with a relative path from the program
[Python] How to get a value with a key other than value with Enum
Get the formula in an excel file as a string in Python
Solve the subset sum problem with a full search in Python
[Golang] Check if a specific character string is included in the character string
What to do when the value type is ambiguous in Python?
[Python] What is a with statement?
Replace dictionary value with Python> update ()
[python] What is the sorted key?
List of language codes used in twitter (including API) (with Python dictionary). What is the most commonly used language?
Python in is also an operator
The story of making a tool to load an image with Python ⇒ save it as another name
How to input a character string in Python and output it as it is or in the opposite direction.
Python> None / True / False> if src is None: / Syntax: a is b / Function: is_ (a, b)> is: Is the object the same / id (a) / ==: Is it the same value / Flyweight pattern / Use == for numerical comparison
What to do if there is a decimal in python json .dumps