[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement

[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement

Summary of dictionary type array.

  1. [Create a dictionary type list](#Create a dictionary type list)
  2. [Create with string](#Create with string)
  3. [Create with numerical value](# Create with numerical value)
  4. [Use operator](use # operator)
  5. [Create with variable](#Create with variable)
  6. [Duplicate key](Duplicate # key)
  7. [Pattern and type that causes an error](#Pattern and type that causes an error)
  8. [Call non-existent key](#Call non-existent key)
  9. [Specify by index number](#Specify by index number)
  10. [The parentheses are different](# The parentheses are different)
  11. [String is not quoted](#String is not quoted)
  12. [Add / Change / Delete Element](# Add / Change / Delete Element)
  13. Add
  14. Change
  15. Delete
  16. [del statement](#del statement)
  17. [pop method](#pop method)
  18. [Delete All](#Delete All)
  19. [Extract one by one with the for statement](Extract one by one with the #for statement)

Create a dictionary-type list

Variable name = {key 1: element 1, key 2: element 2, ,,,,,} └ {} Enclose in curly braces └ Give each element a name (key) └ Connect keys and elements with ":" (writing style similar to css) └ Element extraction is specified by key └ Operators can also be used for keys and elements └ Elements are in the same order (cannot be specified by index number)

① Create with a character string

python


lists1 = {'a':'AAA', 'b':'BBB', 'c':'CCC'}

print(lists1)
{'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}

print(lists1['c'])
CCC

② Created numerically

python


lists2 = {1:111, 2:222, 3:333}

print(lists2)
{1: 111, 2: 222, 3: 333}

print(lists2[2])
222

It is considered as the value of the key, not the index number (because the key can also be set to a number)

③ Use operators

lists3 = {1:5*6, 'a':30/6, 2*8:'AAA'+'BBB'}

print(lists3)
{1: 30, 'a': 5.0, 16: 'AAABBB'}

print(lists3[1])
30

print(lists3['a'])
5.0

print(lists3[16])
AAABBB

The processed value is stored in the array

④ Create with variables

x=1000
y='try'
listsA = {'a':'AAA', 'b':'BBB', 'c':'CCC'}
listsB = [111, 222, 333]

lists4 = {'a':x, 'b':y, 'c':listsA, 'd':listsB}

print(lists4)
{'a': 1000, 'b': 'try', 'c': {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}, 'd': [111, 222, 333]}

You can also use array variables.

⑤ Duplicate keys

lists5 = {5:'CCC', 5:'BBB', 5:'AAA', 5:333, 5:999}

print(lists5)
{5: 999}

print(lists5[5])
999

No error occurs. Only the last one element is stored. * Overwrite at the beginning or in order


## Patterns and types that cause errors ### ① Call a key that does not exist

python


lists = {'a':'AAA', 'b':'BBB', 'c':'CCC'}

print(lists['f'])
KeyError: 'f'

Error type: KeyError

② Specify by index number

python


lists = {'a':'AAA', 'b':'BBB', 'c':'CCC'}

print(lists[2])
KeyError: 2

Error type: KeyError It is considered as the key value, not the index number. Error because key = 2 does not exist

③ The parentheses are different

lists = ['a':'AAA', 'b':'BBB', 'c':'CCC']
print(lists)

SyntaxError: invalid syntax

Error type: SyntaxError {} An error will occur if you use parentheses [] instead of curly braces.

④ The character string is not enclosed in quotation marks

lists1 = {'a':'AAA', b:'BBB', 'c':'CCC'}

print(lists1)
NameError: name 'b' is not defined

Error type: NameError Considered a variable. An error will occur because it is not defined.


## Add / change / delete elements

add to

Array name [key name you want to add] = value you want to add

lists1 = {'a':'AAA', 'b':'BBB', 'c':'CCC'}

#add to
lists1['d']='ddd'
lists1[3]=333

print(lists1)
{'a': 'AAA', 'b': 'BBB', 'c': 'CCC', 'd': 'ddd', 3: 333}

Change

Array name [key name you want to change] = value you want to change └ Overwrite the original element └ Key name cannot be changed

lists1 = {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}

#Change
lists1['b']=999
lists1['c']='GGG'

print(lists1)
{'a': 'AAA', 'b': 999, 'c': 'GGG'}

Delete

① del sentence

del array name [key name you want to delete] └ For non-existent keys KeyError

lists1 = {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}
del lists1['c']

print(lists1)
{'a': 'AAA', 'b': 'BBB'}

② pop method

Array name.pop (key name you want to delete) └ For non-existent keys KeyError

lists1 = {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}
del lists1['a']

print(lists1)
{'b': 'BBB', 'c': 'CCC'}

④ Delete all

Array name.pop (key name you want to delete) └ For non-existent array NameError

lists1 = {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}
lists1.clear()

print(lists1)
{}

## Extract one by one with a for statement
for [Name given to the key] in [Array name]:
processing

└ The name given to the key is arbitrary. Valid only in for statements └ It is the key (not the value) to extract one by one └ Get value array name [name given to key]

▼ Example

lists = {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}

for list_key in lists:
    print(f'Key:{list_key}value:{lists[list_key]}') 

#output
Key: a value:AAA
Key: b value:BBB
Key: c value:CCC

Recommended Posts

[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
How to write a list / dictionary type of Python3
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
How to get dictionary type elements of Python 2.7
[Python] Create a list of date and time (datetime type) for a certain period
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
[Introduction to Python] How to get the index of data with a for statement
[Python] How to create a 2D histogram with Matplotlib
Python # How to check type and type for super beginners
Python list, for statement, dictionary
[Python] I want to use only index when looping a list with a for statement
How to convert an array to a dictionary with Python [Application]
[python] Summary of how to retrieve lists and dictionary elements
[Python] Create a date and time list for a specified period
How to define multiple variables in a python for statement
How to create dataframes and mess with elements in pandas
[Python] How to delete rows and columns in a table (list of drop method options)
[Python] How to create a table from list (basic operation of table creation / change of matrix name)
Python> list> append () and extend ()> append: list is added | extend: list elements are added | + = to add list
How to compare lists and retrieve common elements in a list
Create a striped illusion with gamma correction for Python3 and openCV3
[Python] How to add rows and columns to a table (pandas DataFrame)
How to make a surveillance camera (Security Camera) with Opencv and Python
I tried to create a list of prime numbers with python
How to create a label (mask) for segmentation with labelme (semantic segmentation mask)
Move data to LDAP with python Change / Delete (Writer and Reader)
How to delete multiple specified positions (indexes) in a Python list
How to add a package with PyCharm
[Python] How to convert a 2D list to a 1D list
[Python] How to extract / delete / convert a matrix containing missing values (NaN)
Challenge to create time axis list report with Toggl API and Python
[Introduction to Python] How to judge authenticity with if statement (True and None)
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
[Python] List Comprehension Various ways to create a list
[python] How to display list elements side by side
How to read a CSV file with Python 2/3
How to create a Python virtual environment (venv)
How to clear tuples in a list (Python)
Create a LINE BOT with Minette for Python
How to create a JSON file in Python
How to make a dictionary with a hierarchical structure.
Zip-compress any file with the [shell] command to create a file and delete the original file.
How to add a Python module search path
How to use Service Account OAuth and API with Google API Client for python
Steps to create a Twitter bot with python
How to write a ShellScript Bash for statement
How to create a shortcut command for LINUX
How to create a multi-platform app with kivy
How to get a list of files in the same directory with python
How to remove duplicate elements in Python3 list
[Python] How to write type annotations for Callable objects treated as variables and arguments
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
How to check in Python if one of the elements of a list is in another list
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
How to convert / restore a string with [] in python
[Python] [Django] How to use ChoiceField and how to add options
How to add help to HDA (with Python script bonus)
How to convert Python # type for Python super beginners: str