元组,字典

元组——只读列表,只有count和index两个函数

names=('alex','jack')

print(names.index('jack'))
print(names.index('alex'))

print(names.count('alex'))

元组:各项之间是无序的;每一项都是有key和value组成。
info={'stu001': 'tenglan Wu',
'stu002': 'longze zhang',
'stu003': 'xingxing Liu'}
print(info)

# 增
info['stu004'] = 'aboluo'
print(info)
{'stu003': 'xingxing Liu', 'stu001': 'tenglan Wu', 'stu004': 'aboluo', 'stu002': 'longze zhang'}
# 删
del info['stu001']
print(info)
{'stu003': 'xingxing Liu', 'stu004': 'aboluo', 'stu002': 'longze zhang'}

info.pop('stu002')
print(info)
{'stu003': 'xingxing Liu', 'stu004': 'aboluo'}

# 改
info['stu003'] = '刘星星'
print(info)
{'stu003': '刘星星', 'stu004': 'aboluo'}

# 查
# 若存在,返回value;否则,返回None
print(info.get('stu003'))
刘星星

print(info.get("007"))
None
# 判断key是否在info中
print("stu001" in info)
False


b={'stu001':'Alex',
1:3,
2:5}
#更新(合并)
info.update(b)
print(info)
{1: 3, 2: 5, 'stu001': 'Alex', 'stu003': '刘星星', 'stu004': 'aboluo'}

#将字典转成含有元祖的列表
print(info.items())
dict_items([(1, 3), (2, 5), ('stu001', 'Alex'), ('stu003', '刘星星'), ('stu004', 'aboluo')])

#初始化新的字典
d=dict.fromkeys([6,7,8],["test1","test2"])
d[7][1]='name'
print(d)
{8: ['test1', 'name'], 6: ['test1', 'name'], 7: ['test1', 'name']}
#字典的循环
for i in info:
print(i ,info[i])

#字典转列表,再遍历,较慢(不建议使用)
for k,v in info.items():
print(k,v)

1 3
2 5
stu001 Alex
stu003 刘星星
stu004 aboluo

 
 
原文地址:https://www.cnblogs.com/ceceliahappycoding/p/8299036.html