[PYTHON] Memo "Automate the Boring stuff -chapter5 Dictionaries and Structuring Data"

Dictionaries and Structuring Data

The Dictionary Data Type

>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

>>> myCat['size']
'fat'

>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'

>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}

Dictionaries vs. Lists

>>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    spam['color']
KeyError: 'color'

The keys(), values(), and items() Methods

>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
        print(v)

red
42

>>> for k in spam.keys():
        print(k)

color
age

>>> for i in spam.items():
        print(i)

('color', 'red')
('age', 42)
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
        print('Key: ' + k + ' Value: ' + str(v))

Key: age Value: 42
Key: color Value: red

Checking Whether a Key or Value Exists in a Dictionary

>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False

The get() Method

>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'

The setdefault() Method

Pretty Printing

Using Data Structures to Model Real-World Things

A Tic-Tac-Toe Board

Nested Dictionaries and Lists

Fantasy Game Inventory

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total = item_total + v
    print("Total number of items: " + str(item_total))

displayInventory(stuff)

List to Dictionary Function for Fantasy Game Inventory

Recommended Posts

Memo "Automate the Boring stuff -chapter5 Dictionaries and Structuring Data"
Memo "Chapter 5 – Dictionaries and Structuring Data"
[Personal memo] Get data on the Web and make it a DataFrame
[Python] Chapter 04-06 Various data structures (creating dictionaries)
Python data structure and operation (Python learning memo ③)