Day 5 Python 从入门到实践:字典

  • 字典 ——一系列键值对
alien_0={"color": "green"}
#"color"为键,"green"为与之对应的值
print(alien_0["color"])
  • 访问字典中的值
alien_0={"color": "green", "points": 5}
new_points = alien_0["points"]
print("You just earn "+str(new_points)+" points !")
  • 添加键值对
alien_0={"color": "green", "points": 5}
print(alien_0)
alien_0["x_positions"] = 0
alien_0["y_positions"] = 25
print(alien_0)
  • 修改字典中的值
alien_0={"color": "green"}
print(alien_0["color"])
alien_0["color"] = "yellow"
print(alien_0["color"])
  • 删除键值对
alien_0={"color": "green", "points": 5}
print(alien_0)
del alien_0["color"]#彻底删除
print(alien_0)
  • 多行字典设置
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
    }
print("Sarah's favorite language is "+favorite_languages["sarah"].title()
+"!")
  • 遍历字典
user_0 = {
    "username": "efermi",
    "first": "enrico",
    "last": "fermi",
    }
for key, value in user_0.items():
    print("\nKey: "+key)
    print("value: "+value)#方法item()返回字典中每一个键值对
  • 遍历字典中的键
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
    }
for name in favorite_languages.keys():
    print(name.title())#keys()方法返回字典中所有键,实际为一个包含所有键名的列表
  • 遍历字典中所有值
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
    }
for language in favorite_languages.values():
    print(language.title())#values()方法返回字典中所有值的列表
  • 集合—类似于列表,但元素应当独一无二,不可重复
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
    }
for language in set(favorite_languages.values()):
    print(language.title())
  • 嵌套—有时候需要讲一系列字典存储在列表中,或将列表作为值储存在字典中
alien_0 = {"color": "green", "points": 5}
alien_1 = {"color": "yellow", "points": 10}
alien_2 = {"color": "red", "points": 15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)
  • 将列表存储在字典中—适用于一个键对应于多个值
pizza = {"crust": "thick", "toppings": ["mushrooms","extra cheese"]}
print("You ordered a "+
    pizza["crust"]+"-crust pizza "+
    "with the following toppings:")
for topping in pizza["toppings"]:
    print("\t"+topping)
  • 在字典中储存字典
users = {
    "aeinstein": {
        "first": "albert",
        "last": "einstein",
        "location": "princeton",
        },
    "mcurie": {
        "first": "marie",
        "last": "curie",
        "location": "paris",
        },
    }
for user_name,user_info in users.items():
    print("\nUsername: "+user_name)
    full_name = user_info["first"] +" "+user_info["last"]
    location = user_info["location"]
    print("\t Full name: "+full_name)
    print("\t Location: "+location)

你可能感兴趣的:(学习记录,python)