environment windows7 (I want a Mac Book Pro 16inch) Visual Studio Code chrome python ver3.8.3
This article is written for beginners in programming and Python.
Creating a dictionary isn't difficult, but as a super beginner I make a few mistakes.
First of all, how to make a dictionary type.
{}
Write the key and value in curly braces.
The key is described in {}
with the name of the key and : (colon)
, and the value is described after : (colon)
.
One of the things I tend to make mistakes at this time is to enclose the keys and values in " "
when writing strings.
I will forget ... Please be careful.
Write key 1: value 1
, followed by, (comma)
.
dict.py
{ "Key 1":"Value 1","Key 2":"Value 2","Key 3":"Value 3,・ ・ ・ ・ ・ ・}
Now that you have created a dictionary type, you can use this dictionary type. The value corresponding to the key is extracted as follows.
dict.py
academy_awards = {"Green book": 2019, "Chicago": 2003, "Titanic": 1998}
print(academy_awards["Green book"])
#2019
If you specify a key that is not set (does not exist) in the created dictionary type, an Error will occur.
However, if you use the .get method
and specify a key that is not set (does not exist), then None
Will be returned.
dict.py
academy_awards = {"Green book": 2019, "Chicago": 2003, "Titanic": 1998}
print(academy_awards["Joker"])
#KeyError: 'Joker'
print(academy_awards.get("Joker"))
#None
If the .get method
describes a string as the second argument, it will be the second if the key does not exist.
Returns an argument.
dict.py
academy_awards = {"Green book": 2019, "Chicago": 2003, "Titanic": 1998}
print(academy_awards.get("Joker", "The movie does not exist in the Best Picture"))
#The movie does not exist in the Best Picture
In addition, you can retrieve all keys, retrieve all values, and retrieve all keys and values.
Use .keys ()
, .values ()
, and .items ()
, respectively.
python.dict.py
academy_awards = {"Green book": 2019, "Chicago": 2003, "Titanic": 1998}
print(academy_awards.keys()) #Take out the key
#dict_keys(['Green book', 'Chicago', 'Titanic'])
print(academy_awards.values()) #Retrieve value
#dict_values([2019, 2003, 1998])
print(academy_awards.items()) #Take out everything
#dict_items([('Green book', 2019), ('Chicago', 2003), ('Titanic', 1998)])
fin
Python #Hello World for super beginners
Python for super beginners and super beginners # Easy to get confused
Python #type (type) and how to check type (type) for super beginners of Python
How to convert Python # type for Python super beginners: str edition
How to convert Python # type for Python super beginners: int, float edition
Read Python # .txt file for super beginners in Python with working .py
Python #Function 1 for Python Super Beginners
Python #Function 2 for super beginners of Python
[Python #len function for super beginners of Python] (https://qiita.com/Macchino5/items/a64347f9e832406d3c24)
Python #list for super beginners of Python
Python #index for super beginners, slices
Recommended Posts