笨方法学Python 习题39

这里是列表举例

things = ["a", "b", "c", "d"]
print(things[1])

things[1] = "z"

print(things[1])

print(things)

这里是字典举例

stuff = {"name": "fuzhuo", "age" : "19", "height" :"111"}
print(stuff["name"])

print(stuff["age"])

print(stuff["height"]) #键是字符串

stuff["city" ] = "JS" #dic中新增一组键值对

print(stuff["city"])

stuff[1] = "Wow"
stuff[2] = "hei" #键值对中键是数字

print(stuff[1])

print(stuff[2])

del stuff["city"]
print(stuff)

del stuff[1]
print(stuff)

中括号括起来的键值对元祖数据组合成的列表,就是字典。字典是无序的,所以字典内部的元素顺序排列不一样,只要内容不变,就还是同一个字典数据结构。
del是个python里面的关键词,用法是删除某个数据结构中的一个元素。

这里是正文代码

# =============================================================================
# create a mapping of state to abbreviation 
# =============================================================================
states = {
    "Oregon": "OR",
    "Florida": "FL",
    "Carlifornia": "CA",
    "New York": "NY",
    "Michigan": "MI"
    }

# =============================================================================
# create a basic set of states and some cities in them
# =============================================================================
cities = {
    "CA": "San Francisco",
    "MI": "Detroit",
    "FL": "Jacksonville",
    }

# =============================================================================
# add some more cities
# =============================================================================
cities["NY"] = "New York"
cities["OR"] = "Portland"

# =============================================================================
# print out some cities
# =============================================================================
print("-" * 10)
print("NY state has: ", cities["NY"])
print("OR state has: ", cities["OR"])

# =============================================================================
# print some states
# =============================================================================
print("-" *10)
print("Michigan's abbreviation is: ", states["Michigan"])
print("Florida's abbreviation is: ", states["Florida"])

# =============================================================================
# do it by using the state then cities dict
# =============================================================================
print("-" *10)
print("Michigan has:", cities[states["Michigan"]])
print("Florida has: ", cities[states["Florida"]])

# =============================================================================
# print every state abbreviation
# =============================================================================
print("-" *10)
for state, abbrev in list(states.items()): #items()函数是个新东西
    print(f"{state} is abbreviated {abbrev}")

# =============================================================================
# print every city in state
# =============================================================================
print("-" *10)
for abbrev, city in list(cities.items()):
    print(f"{abbrev} has the city {city}")

# =============================================================================
# now do both at the same time
# =============================================================================
print("-" *10)
# for state, abbrev in list(states.items()):
# for state, abbrev in states.items(): #这个代码也可以运行成功
for (state, abbrev) in states.items(): #这个代码也可以运行成功
    print(f"{state} state is abbreviated {abbrev}")
    print(f"and has city {cities[abbrev]}")

# =============================================================================
# states.items()
# Out[6]: dict_items([('Oregon', 'OR'), ('Florida', 'FL'), ('Carlifornia', 'CA'), ('New York', 'NY'), ('Michigan', 'MI')])
# 看到items()函数给出键值对组成的元祖不可动,然后再组成一个list
# 这里list函数
# 以上三行代码都可以,加括号表示tuple类型,list()函数转换成列表
# 
# =============================================================================
print("-" *10)
# =============================================================================
# safely get a abbreviation by state that might not be there
# =============================================================================
state = states.get("Texas")

if not state:
    print("Sorry, no Texas.")
    
# =============================================================================
# get a city with a default value 不存在给出默认值
# Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值
# =============================================================================
city = cities.get("TX", "Does Not Exist")
print(f"The city for the state 'TX' is: {city}")
# =============================================================================
# 语法是 dict.get(key, default=None)
# 
# key -- 字典中要查找的键。
# 
# default -- 如果指定键的值不存在时,返回该默认值
# 
# 这里 key 就是 Texas,意思就是要查找它,然后找不到就返回None
# =============================================================================

这里是拓展练习

关于如何获得有序字典,import模块collections,然后操作。

import collections

dic01=collections.OrderedDict()# 新建一个有序字典数据结构
dic01[10] = 11
dic01[20] = 22
dic01[30] = 33

print(dic01)
# =============================================================================
# 按照创建元素的顺序来排列,既然有序,这里我来试试dic01[0]会是什么
# =============================================================================
# =============================================================================
# print(dic01[0]) #出错了,再试试 KeyError: 0
# =============================================================================
# print(list(dic01.item())[0]) # 也出错了
# AttributeError: 'collections.OrderedDict' object has no attribute 'item'
# =============================================================================
# =============================================================================

dic02=collections.OrderedDict()
dic02[30] = 33
dic02[20] = 22
dic02[10] = 11

print(dic02)

print(dic01 == dic02)

得出结果是:

OrderedDict([(10, 11), (20, 22), (30, 33)])
OrderedDict([(30, 33), (20, 22), (10, 11)])
False

由此可知,这两个字典,虽然内容完全一样,但是是不一样的字典,因为是此处的字典是有序的。

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值