【问题标题】:python: read and split files in to list of dictionariespython:将文件读取并拆分到字典列表中
【发布时间】:2011-12-25 10:14:52
【问题描述】:

我在将文件内容转换为字典列表时遇到问题,您能建议吗?

File content:
host1.example.com#192.168.0.1#web server 
host2.example.com#192.168.0.5#dns server
host3.example.com#192.168.0.7#web server 
host4.example.com#192.168.0.9#application server 
host5.example.com#192.168.0.10#database server

文件夹中有多个格式相同的文件。最后,我想收到以下格式的字典列表:

[ {'dns': 'host1.example.com', 'ip': '192.168.0.1', 'description': 'web_server'},
{'dns': 'host2.example.com', 'ip': '192.168.0.5', 'description': 'dns server'}, 
{'dns': 'host3.example.com', 'ip': '192.168.0.7', 'description': 'web server'}, 
{'dns': 'host4.example.com', 'ip': '192.168.0.9', 'description': 'application server'},
{'dns': 'host5.example.com', 'ip': '192.168.0.10', 'description': 'database server'} ]

提前谢谢你!

【问题讨论】:

    标签: python file list dictionary split


    【解决方案1】:
    >>> map(lambda x : dict(zip(("dns", "ip", "description"), tuple(x.strip().split('#')))), open('input_file'))
    

    【讨论】:

    • 我喜欢map 和下一个家伙一样多,但最近大力推动使用列表推导。请参阅 Shawn Chin 的回答。
    【解决方案2】:

    假设你的文件是infile.txt

    >>> entries = (line.strip().split("#") for line in open("infile.txt", "r"))
    >>> output = [dict(zip(("dns", "ip", "description"), e)) for e in entries]
    >>> print output
    [{'ip': '192.168.0.1', 'description': 'web server', 'dns': 'host1.example.com'}, {'ip': '192.168.0.5', 'description': 'dns server', 'dns': 'host2.example.com'}, {'ip': '192.168.0.7', 'description': 'web server', 'dns': 'host3.example.com'}, {'ip': '192.168.0.9', 'description': 'application server', 'dns': 'host4.example.com'}, {'ip': '192.168.0.10', 'description': 'database server', 'dns': 'host5.example.com'}]
    

    【讨论】:

      【解决方案3】:

      首先,您要拆分# 上的每一行。然后,您可以使用zip 将它们与标签一起压缩,然后将其转换为字典。

      out = []
      labels = ['dns', 'ip', 'description']
      for line in data:
          out.append(dict(zip(labels, line.split('#'))))
      

      那一行有点复杂,所以分解一下:

      # makes the list ['host2.example.com', '192.168.0.7', 'web server']
      line.split('#')  
      
      # takes the labels list and matches them up:
      # [('dns', 'host2.example.com'),
      #  ('ip', '192.168.0.7'),
      #  ('description', 'web server')]
      zip(labels, line.split('#'))  
      
      # takes each tuple and makes the first item the key,
      #  and the second item the value
      dict(...)  
      

      【讨论】:

      • 其实,你的答案是我个人会做的,但不幸的是,list comps 让大多数人感到困惑。也为你 +1。
      【解决方案4】:
      rows = []
      for line in input_file:
          r = line.split('#')
          rows.append({'dns':r[0],'ip':r[1],'description':r[2]})
      

      【讨论】:

        猜你喜欢
        • 2015-06-23
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        • 2018-06-22
        • 2017-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多