python字典中如何一键多值的写入?


当前第2页 返回上一页

其中格式{key:[value1,value2,...]}

文本txt格式如下:

  • guaguashipinliaotianshi|.guagua.cn,

  • guaguashipinliaotianshi|iguagua.net,

  • guaguashipinliaotianshi|.17guagua.com,

  • jiuxiumeinvzhibo|.69xiu.com,

  • nbazhibo|.estream.cn,

  • youbo|yb.sxsapp.com,


其中第一列的名字有重复想要一个名字对应多个结果,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

def makehostDict():

    host_dict={}

    f_allhost=open('xml_host.txt','rb')

    lines=f_allhost.readlines()

    for line in lines:

        line_list=line.split('|')

        name=line_list[0]

        host=line_list[1].strip('\n')

        if host is not '':

            if  host_dict.has_key(name):

                host_dict.get(name).append(host)#此处为关键向字典里已经有的key(name)值后继续添加value(host)

            else:

                host_dict.setdefault(name,[]).append(host)#创建{name,[host]}value为列表的格式的字典。

    return host_dict

host_dict=makehostDict()

print host_dict

推荐教程:《python视频教程》

以上就是python字典中如何一键多值的写入?的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python如何判断整数

Python如何实现杨辉三角形 (代码)

Python识别图片中文字的方法

Python数据结构:一个被低估的namedtuple(一)

Python格式化输出是什么意思

Python可以写病毒吗

Python函数之chr(i)

关于Python中原始字符串与unicode字符串操作符的实例

Python字典一个键只能有一个值吗

详解Python中and和or的返回值

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...