Dict字典的操作

字典的操作

1.字典新增键值对

已存在内容的字典新增

alient_0 = {"color":"green",position:10}
alient_0["x_position"]= 1
alient_0["y_position"] = 2
print(alient_0)

空字典新增

alient_0 = {}
alient_0["color"] = "green"
alient_0["position"] = 10

2. 字典修改键值对

#修改字典键-值对
alien_2 = {'color':'green','points':9}
print("alient_2的颜色是:",alien_2['color'])
alien_2['color'] = 'yellow'
print("alient_2现在的颜色是:",alien_2['color'])

3. 字典删除键值对


del方法:删除指定的键值对

pop方法:根据指定键,删除指定键值对

popitem方法:删除最有一个键值对

clear方法:清空所有的键值对

alien_3 = {'color':'green','points':5}
print("删除前",alien_3)
del alien_3['points']
print("删除后",alien_3)

4. 查询内容

alien_3 = {'color':'green','points':5}
color = alien_3['color']

遍历字典

  • 遍历key,value值

    user = {}
    user.items

#遍历字典
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user_0.items
    print("\nKey:"+key)
    print("\nValue:"+value)

5.遍历key值

#遍历字典中的所有键
favorite_languages = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for name in favorite_languages.keys():
    print(name.title())

6.遍历value值

#遍历字典中的所有值
favorite_languages = {
'username': 'english',
'first': 'chinese',
'last': 'French',
}
for language in favorite_languages.values():
    print(language.title())

字典嵌套

  • 列表里嵌套字典

  • 字典里嵌套列表
#存储所点披萨的信息
pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
    }

print("披萨的配料有:",pizza['toppings'])
  • 字典里嵌套字典
users = {
    '这里我最屌':{
        "姓":"小",
        "名":"明",
        "住址":"山卡拉"
    },
    '看谁最屌':{
        "姓":"小",
        "名":"红",
        "住址":"大都市"
    },
    }
for username,userinfo in users.items():
    full_name = userinfo["姓"]+userinfo["名"]
    location = userinfo["住址"]
    print("用户名:\n"+username+"\n用户信息:\n姓名:"+full_name+" 住址:"+location)

猜你喜欢

转载自www.cnblogs.com/yangsun/p/10163871.html