Python 字典的理解

Python的数据结构:字典,最主要的概念就是键-值对,键所对应的值可以是str/dict/list等。
在我做一重字典嵌套的键值打印时,以下加星号部分代码出现错误,在items中,每对 键值对 以元组形式出现,元组不能以星号部分代码形式进行print。

notes={'lili':{'电话': 1837326512,'住址':'xjewidhe'},'loyt':{'电话': 1454576512,'住址':'vrfvdhe'}}

for name in notes.items():
  print (type(name))
  print(name)
  ****print('联系人 %s 的电话号码是 %s , 地址是 %s'%(name,notes[name]['电话'],notes[name]['住址']))****

在语句 for name,content in notes.items():中,
name 是‘键’key的变量,‘content’是‘值’value的变量,key此处是字符串,value此处是字典,content['电话'] 语句可行。
在语句 for name in notes.items():中,items()以元组的列表形式存在
[('lili', {'电话': 1837326512, '住址': 'xjewidhe'}), ('loyt', {'电话': 1454576512, '住址': 'vrfvdhe'})]

完整代码如下

#!/usr/bin/env python
# -*- coding:utf-8 -*-

notes={'lili':{'电话': 1837326512,'住址':'xjewidhe'},'loyt':{'电话': 1454576512,'住址':'vrfvdhe'}}

for name,content in notes.items():
  print (type(name))
  print (type(content))
  print('联系人 %s 的电话号码是 %s , 地址是 %s'%(name,content['电话'],content['住址']))
for name in notes.items():
  print (type(name))
  print(name)
  print('联系人 %s 的电话号码是 %s , 地址是 %s'%(name,notes[name]['电话'],notes[name]['住址']))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值