Python 字典笔记

一、字典

  1、功能与列表功能一样

  2、使用 in 或 not in 判断索引是否存在

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12'}
'Alice' in birthdays # True
'Jack' in birthdays # False

  3、使用 values() 获取所有值

spam = {'color': 'red', 'age': 42}
spam # {'red', 42},可以使用 for 循环遍历

  4、使用 keys() 获取所有键

spam = {'color': 'red', 'age': 42}
spam # {'age', 'color'},可以使用 for 循环遍历

  5、使用 items() 获取所有的键与值,键与值分别放在不现的字典中

spam = {'color': 'red', 'age': 42}
spam # {{'age', 'color'},{'red', 42}},可以使用 for 循环遍历

  6、使用 get()获取值,如果值不存在,使用第二个参数作为默认值

picnicItems = {'apples': 5, 'cups': 2}
picnicItems.get('cups', 0) #2
picnicItems.get('orange', 0) #0

  7、使用 setdefault()为字典中的键的值,如果键不存在,使用第二个参数设置默认值

spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black') # {'name': 'Pooka', 'age': 5, 'color': 'black'}

spam = {'name': 'Pooka', 'age': 5, 'color': 'white'}
spam.setdefault('color', 'black') # {'name': 'Pooka', 'age': 5, 'color': 'white'}

  8、使用pprint 格式化打印,pformat() 返回格式化字符串 需要先引入 pprint

import pprint
pprint.pprint(dirc) # 打印格式化后的结果
pprint.pformat(dirc) # 返回格式化后字符串

  

二、字典与列表对比

  1、和列表一样,有许多值(表项)

  2、字典的索引可以有不同类型数据,而列表只是整数

  3、列表使用中括号 [],字典使用花括号 {}

myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'} # 字典
myCat = ['fat', 'gray', 'loud'] # 列表

  4、字典的索引不排序,列表的索引是排序

 

三、案例

  1、物品清单整理

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

'''
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
'''


def add_to_inventory(inventory, added_items):
    # your code goes here
    for i in added_items:
        if i in inventory:
            inventory[i] += 1
        else:
            inventory[i] = 1
    return inventory

inv = {'gold coin': 42, 'rope': 1} # 字典
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # 列表

inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)

  

posted @ 2018-04-12 10:00  lampjia  阅读(259)  评论(0编辑  收藏  举报