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'}

你可能感兴趣的:(python)