python入门5:字典、遍历字典、字典嵌套

字典

字典:{},一系列键-值对应、关联,使用时,用键来访问关联的值[键];
字典:{键:值,-}与键关联的可以是数字、字符串、列表、字典等任何对象;
访问字典中的值:name[键]即可返回值;
添加键-值对:name[键]=值即可添加,不关心顺序;
创建一个空字典:{},然后添加键-值对即可;
修改字典中的值:name[键]=新的值即可修改成功;
删除键-值对:del name[键],指定字典名和要删除的键,永远删除;
多个对象组成的字典:回车 - 空格 - 逗号;

ymj = {"age":22, "school":"CUG&UCAS", "gender":"girl"}
print(ymj["age"])
ymj["hometwon"] = "shandong"
print(ymj)

#创建一个空字典
time = {}
time["nian"] = 2022
time["yue"] = 2
time["ri"] = 24
print(time)

#删除
del ymj["age"]
print(ymj)
22
{'age': 22, 'school': 'CUG&UCAS', 'gender': 'girl', 'hometwon': 'shandong'}
{'nian': 2022, 'yue': 2, 'ri': 24}
{'school': 'CUG&UCAS', 'gender': 'girl', 'hometwon': 'shandong'}
infos = {"age":22, "school":"CUG&UCAS", "gender":"girl"}
for info in infos:
    print(info + ":" + str(infos[info]))
    
numbers = {"ymj":2, "Ymj":3, "YMj":4,"YMJ":5}
for number in numbers:
    print(number + ":" +str(numbers[number]))
    print("Are you sure this is your favoriate number?")

vocabularies = {
    "list":"列表", 
    "del":"永久删除", 
    "sort()":"永久分类",
    }
for vocabulary in vocabularies:
    print(vocabulary + ":" + str(vocabularies[vocabulary]))
age:22
school:CUG&UCAS
gender:girl
ymj:2
Are you sure this is your favoriate number?
Ymj:3
Are you sure this is your favoriate number?
YMj:4
Are you sure this is your favoriate number?
YMJ:5
Are you sure this is your favoriate number?
list:列表
del:永久删除
sort():永久分类

遍历字典

遍历所有键-值对:获取字典中的所有信息,for key,value in name.items();
遍历所有键:获取键,for key in name.keys(),.keys()可省略;
按照顺序遍历所有键:sorted();
遍历所有值:for value in name.values();
集合:当值出现大量重复时,剔除重复项,set();

#遍历所有键-值
name = {"first":"mj", "last":"yuan"}
for key,value in name.items():
    print("key:" + key)
    print("value:" + value)
    
#遍历所有键、值
ymj = {"age":22, "school":"CUG&UCAS", "gender":"girl"}
information = ["age", "school"]
for key in ymj.keys():
    print(key.title())
    if key in information:
        print("I can do it!")
    
    for value in ymj.values():
        print(str(value).title())
if "year" not in ymj.keys():
    print("Add it.") 
    
#按照顺序遍历键
ymj = {"age":22, "school":"CUG&UCAS", "gender":"girl","herage":22}
for information in sorted(ymj.keys()):#可以将sorted直接放在这里进行排序
    print(information.title())
    
#集合
ymj = {"age":22, "school":"CUG&UCAS", "gender":"girl","herage":22}
for values in set(ymj.values()):#set去掉值的重复项
    print(values)
key:first
value:mj
key:last
value:yuan
Age
I can do it!
22
Cug&Ucas
Girl
School
I can do it!
22
Cug&Ucas
Girl
Gender
22
Cug&Ucas
Girl
Add it.
Age
Gender
Herage
School
girl
CUG&UCAS
22

嵌套

嵌套:就是套娃呗,字典存在列表中,列表存在字典中,字典存在字典中;
字典列表:把创建好的非空字典放到一个列表中即可;
列表字典:适用于一个对象对应多个值的场景,把列表放在字典中;
字典字典:适用于多个用户且每个用户都有多个信息的场景;

#字典列表
num1 = {"x":20, "y":30}
num2 = {"x":10, "y":20}
num3 = {"x":30, "y":40}
nums = [num1, num2, num3]
for num in nums:
    print(num)

#批量生成
nums = []
for num_number in range(10):#批量生成10个字典
    new_num = {"x":1, "y":1}
    nums.append(new_num)
print(nums[-5:])

#字典中存储列表
fruit = {
    "size":"big",
    "colors":["yellow","green","purple"],
    }
print("You can buy " + fruit["size"] + " fruits with " + "the color:" )
for color in fruit["colors"]:
    print(color)
{'x': 20, 'y': 30}
{'x': 10, 'y': 20}
{'x': 30, 'y': 40}
[{'x': 1, 'y': 1}, {'x': 1, 'y': 1}, {'x': 1, 'y': 1}, {'x': 1, 'y': 1}, {'x': 1, 'y': 1}]
You can buy big fruits with the color:
yellow
green
purple
#字典列表
name1 = {"first":"mj", "last":"Yuan"}
name2 = {"first":"jy", "last":"Cheng"}
name3 = {"first":"yl", "last":"Luo"}
people = [name1, name2, name3]
for name in people:
    print(name)
    
chaichai = {"type":"dog", "owner":"ymj"}
bomei = {"type":"dog", "owner":"ymj"}
yingduan = {"type":"cat","owner":"ymj"}
pets = [chaichai, bomei, yingduan]
for pet in pets:
    print(pet)

#列表字典
favorite_places = {"ymj":["lijiang", "chengdu", "changsha"],
                   "lyl":["1", "2", "3"],
                   "cjy":["4", "5", "6"]    
    }
for name, places in favorite_places.items():
    print(name + "'s favorite places are:")
    for place in places:
        print(place)
        
#字典字典
cities = {"beijing":{"country":"China","truth":"country's capital"},
          "chengdu":{"country":"China","truth":"yumizhixiang"},
          "heze":{"country":"China","truth":"paradise of mudan"},
         }
for name, info in cities.items():
    print(name.title() + " is located in ")
    print(info["country"] + ",")
    print(" and it is the " + info["truth"] + ".")
{'first': 'mj', 'last': 'Yuan'}
{'first': 'jy', 'last': 'Cheng'}
{'first': 'yl', 'last': 'Luo'}
{'type': 'dog', 'owner': 'ymj'}
{'type': 'dog', 'owner': 'ymj'}
{'type': 'cat', 'owner': 'ymj'}
ymj's favorite places are:
lijiang
chengdu
changsha
lyl's favorite places are:
1
2
3
cjy's favorite places are:
4
5
6
Beijing is located in 
China,
 and it is the country's capital.
Chengdu is located in 
China,
 and it is the yumizhixiang.
Heze is located in 
China,
 and it is the paradise of mudan.
  • 31
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值