python字典(一)

字典用于一个储存键值对的类 非常的方便

首先来看一个简单的字典定义

people = {'name' : 'francis','age' : 10}
print(people["name"]) #这里还可以看出单引号双引号是等价的 都存在的意义主要在于处理嵌套关系

 

添加键值对

 

people = {'name' : 'francis','age' : 10}
people['num'] = 123456
print(people['num']) 

 

同时我在使用字典之前可以创建一个空字典然后后续添加 

 

修改键值对 

一一对应的关系 类似于函数的映射 我们修改键值对只需要重新赋值即可

people['age'] = 12

 

删除键值对

del people['age']

 

在使用字典时 往往使用这种书写格式

people = {
        'name' : 'francis',
        'age' : 10,
        'num' : 123456,
        'sex' = 'man',
        }

遍历字典

遍历所有的键值对

people = {
        'name' : 'francis',
        'age' : 10,
        'num' : 123456,
        'sex' : 'man',
        }

for k,v in people.items():
    print('key:' + str(k))
    print('value:' + str(v) +'\n')

 

 遍历字典的所有键

people = {
        'name' : 'francis',
        'age' : 10,
        'num' : 123456,
        'sex' : 'man',
        }

for k in people.keys():
    print('\nkey:' + str(k))

加入排序 

people = {
        'name' : 'francis',
        'age' : 10,
        'num' : 123456,
        'sex' : 'man',
        }

for k in sorted(people.keys()):
    print('\nkey:' + str(k))

 遍历字典的所有值

同理

people = {
        'name' : 'francis',
        'age' : 10,
        'num' : 123456,
        'sex' : 'man',
        }

for v in people.values():
    print('\nkey:' + str(v))

 

嵌套

array1 = {'color':'green','point':5}
array2 = {'color':'yellow','point':6}
array3 = {'color':'blue','point':7}

arrays = [array1 , array2 , array3]

for array in arrays:
    print(array)

arrays = []

for array in range(30):
    new_ele = {'num' : 1 ,'name' : 'Jack'}
    arrays.append(new_ele)
    
for array in arrays[:5]:
    print(array)
    print('..................')
    
print('the num of arr is ' + str(len(arrays)))

 

在字典中储存字典

user = {
        'fcy' :{
            'name':'jack',
            'num':123,
            'location0':'CSU',},
        'zxy':{
            'name':'rose',
            'num':456,
            'location':'SHCU',},
        }
        
for username,userinfo in user.items(): #Python字典items()方法用于返回字典dict的(key,value)元组对的列表
    print(username,userinfo)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值