Python 字典的理解

来源:互联网 发布:天融信网络审计 编辑:程序博客网 时间:2024/06/05 20:05

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]['住址']))
原创粉丝点击