列表中循环添加字典出现覆盖现象的问题

来源:互联网 发布:本地连接 未识别的网络 编辑:程序博客网 时间:2024/05/15 09:01

这是要解析的xml

<user>  <userInfo config="/etc" index="1" ip="172.16.1.239" phone="15011262015" realname="田振华" username="tianzh"/>  <userInfo config="/usr" index="2" ip="1.1.1.1" phone="110" realname="龚凡" username="gongf"/>  <userInfo config="/lib" index="3" ip="2.2.2.2" phone="120" realname="安吉旺" username="anjw"/></user>

这是之前的代码

def get_xml_data(filename='config_new.xml'):    key_list = ["username","index","realname","config","ip","phone"]    doc = minidom.parse(filename)    root = doc.documentElement    user_nodes = root.getElementsByTagName('userInfo') #根据节点名获取节点集合    usersinfo=[]     #键值列表 用户信息集合 一个字典表示一行user信息    adict = {}      for node in user_nodes:        for key in key_list:            value = node.getAttribute(key)  #根据属性名获取属性值            if value.strip():#如果属性值不为空(不是"") 则加入到字典中                adict[key] = value;        print adict        usersinfo.append(adict)        print usersinfo    return usersinfo
本来是想将从xml中获取出来的信息做为键值做成字典放到列表中,结果返回的usersinfo变成了这样:[{'username': u'anjw', 'index': u'3', 'realname': u'\u5b89\u5409\u65fa', 'ip': u'2.2.2.2', 'phone': u'120', 'config': u'/lib'}, {'username': u'anjw', 'index': u'3', 'realname': u'\u5b89\u5409\u65fa', 'ip': u'2.2.2.2', 'phone': u'120', 'config': u'/lib'}, {'username': u'anjw', 'index': u'3', 'realname': u'\u5b89\u5409\u65fa', 'ip': u'2.2.2.2', 'phone': u'120', 'config': u'/lib'}]显然是不对的,后来查了一下资料,自学了几天python,内部实现虽然不知道,但是显然是最后的解析覆盖了之前的,后来在网上看到的例子受到了启发,我觉得是这样的:我们始终都是更新的adict这个对象,而这个对象只创建了一次,append函数添加的时候只是添加了adict这个对象的地址(我也不知道python这个语言有没有地址这个说法,我只是根据之前学的c语言猜测的。。),所以usersinfo经过三次循环usersinfo的变化是这样的[p1]->[p1,p1]->[p1,p1,p1],p1就是adict地址,所以不管我们怎么循环,usersinfo中的字典都是一样的。所以我们应该把adict的创建放到for循环中,每次append的时候都是添加的新的字典对象就可以了解决此问题代 
       def get_xml_data(filename='config_new.xml'):    key_list = ["username","index","realname","config","ip","phone"]    doc = minidom.parse(filename)    root = doc.documentElement    user_nodes = root.getElementsByTagName('userInfo') #根据节点名获取节点集合    usersinfo=[]     #键值列表 用户信息集合 一个字典表示一行user信息    for node in user_nodes:        adict = {}  #临时字典初始化        for key in key_list:            value = node.getAttribute(key)  #根据属性名获取属性值            if value.strip():#如果属性值不为空(不是"") 则加入到字典中                adict[key] = value;        print adict        usersinfo.append(adict)        print usersinfo    return usersinfo

打印usersinfo也正常了

[{‘username’: u’tianzh’, ‘index’: u’1’, ‘realname’: u’\u7530\u632f\u534e’, ‘ip’: u’172.16.1.239’, ‘phone’: u’15011262015’, ‘config’: u’/etc’},
{‘username’: u’gongf’, ‘index’: u’2’, ‘realname’: u’\u9f9a\u51e1’, ‘ip’: u’1.1.1.1’, ‘phone’: u’110’, ‘config’: u’/usr’},
{‘username’: u’anjw’, ‘index’: u’3’, ‘realname’: u’\u5b89\u5409\u65fa’, ‘ip’: u’2.2.2.2’, ‘phone’: u’120’, ‘config’: u’/lib’}]

解决了!

0 0
原创粉丝点击