python字典

使用字典

python的字典由一些列key和value构成,可以用于存放同类的数据,也可以用来存放同属的数据:

scores = { "xiaoming": 60, "xiaohong": 70, "xiaohei": 80}
infos = { "name": "xiaoming", "age": 20, "sex": "female"}

print(scores)
print(infos)

输出:
{'xiaoming': 60, 'xiaohong': 70, 'xiaohei': 80}
{'name': 'xiaoming', 'age': 20, 'sex': 'female'}

访问和修改字典的方式:

scores = { "xiaoming": 60, "xiaohong": 70, "xiaohei": 80}
print(scores["xiaoming"])  #访问

scores["xiaoming"] = 100   #修改
print(scores)

输出:
60
{'xiaoming': 100, 'xiaohong': 70, 'xiaohei': 80}

向字典中添加或删除key-value:

scores = { "xiaoming": 60, "xiaohong": 70, "xiaohei": 80}
scores["xiaomei"] = 90   #添加
print(scores)

del scores["xiaoming"]   #删除
print(scores)

输出:
{'xiaoming': 60, 'xiaohong': 70, 'xiaohei': 80, 'xiaomei': 90}
{'xiaohong': 70, 'xiaohei': 80, 'xiaomei': 90}

遍历字典

同时遍历key和value:

scores = { "xiaoming": 60, "xiaohong": 70, "xiaohei": 80}
for key,value in scores.items():
    print(key, end=':')
    print(value)

输出:
xiaoming:60
xiaohong:70
xiaohei:80

单独遍历key或value:

for key in scores.keys():
    print(key)
    
    
for value in scores.values():
    print(value)
    
输出:
xiaoming
xiaohong
xiaohei
60
70
80

python字典实现基于HashTable,因此它的key-value顺序不定,如果想按照顺序遍历,可以使用sorted进行排序后遍历:

scores = { "xiaoming": 60, "xiaohong": 70, "xiaohei": 80}
for key in sorted(scores.keys()):
    print(key)

输出:
xiaohei
xiaohong
xiaoming

字典和列表混合使用

在列表中存储字典:

person1 = {"name": "xiaoming", "age": 20, "sex": "female"}
person2 = {"name": "xiaohong", "age": 18, "sex": "male"}

persons = [person1, person2]

for person in persons:
    print(person)

输出:
{'name': 'xiaoming', 'age': 20, 'sex': 'female'}
{'name': 'xiaohong', 'age': 18, 'sex': 'male'}

在字典中存储列表:

staples = ["rice", "potato", "corn"]
vegetables = ["cabbage", "carrot"]

foods = {}
foods["staples"] = staples
foods["vegetables"] = vegetables

for key,value in foods.items():
    print(key)
    print(value)
    
输出:
staples
['rice', 'potato', 'corn']
vegetables
['cabbage', 'carrot']

字典中存储字典:

developer = {"numbers": 20, "create_date": "20190427"}
requirementer = {"numbers": 10, "create_date": "20190427"}

developments = {}
developments["developer"] = developer
developments["requirementer"] = requirementer

top_departments = {}
top_departments["development"] = developments

for second_developments in top_departments.values():
    for key,value in second_developments.itmes():
        print(key)
        print(value)

输出:
developer
{'numbers': 20, 'create_date': '20190427'}
requirementer
{'numbers': 10, 'create_date': '20190427'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值