拆分字典键和来自dict的值列表 [英] Split dictionary key and list of values from dict

查看:165
本文介绍了拆分字典键和来自dict的值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拆分键和值,并显示下面提到的格式的字典结果。我正在读取一个文件并将数据分解成列表,然后再移动到字典。

I want to split keys and values and display the dictionary result below mentioned format. I'm reading a file and splitting the data into list and later moving to dictionary.

请帮我取得结果。

INPUT FILE - 命令。 txt

INPUT FILE - commands.txt

login url=http://demo.url.net username=test@url.net password=mytester

create-folder foldername=demo

select-folder foldername=test123

logout

预期结果格式

print result_dict


        "0": {
            "login": [
                {
                    "url": "http://demo.url.net",
                    "username": "test@url.net",
                    "password": "mytester"
                }
            ]
        },
        "1": {
            "create-folder": {
                "foldername": "demo"
            }
        },
        "2": {
            "select-folder": {
                "foldername": "test-folder"
            }
        },
        "3": {
            "logout": {}
        }

代码

    file=os.path.abspath('catalog/commands.txt')
    list_output=[f.rstrip().split() for f in open(file).readlines()]
    print list_output

    counter=0
    for data in list_output:
        csvdata[counter]=data[0:]
        counter=counter+1   
    print csvdata

for key,val in csvdata.iteritems():
    for item in val:
        if '=' in item:
            key,value=item.split("=")
            result[key]=value

print result


推荐答案

作为一个功能:

from collections import defaultdict
from itertools import count

def read_file(file_path):
    result = defaultdict(dict)
    item = count()
    with open(file_path) as f:
        for line in f:
            if not line:
                continue
            parts = line.split()
            result[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:])
    return dict(result)

更好的例子和解释:

s = """
login url=http://demo.url.net username=test@url.net password=mytester

create-folder foldername=demo

select-folder foldername=test123

logout
"""

from collections import defaultdict
from itertools import count

result_dict = defaultdict(dict)
item = count()

# pretend you opened the file and are reading it line by line
for line in s.splitlines():
    if not line:
        continue # skip empty lines
    parts = line.split()
    result_dict[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:])

使用漂亮的打印:

>>> pprint(dict(result_dict))
{0: {'login': {'password': 'mytester',
               'url': 'http://demo.url.net',
               'username': 'test@url.net'}},
 1: {'create-folder': {'foldername': 'demo'}},
 2: {'select-folder': {'foldername': 'test123'}},
 3: {'logout': {}}}

这篇关于拆分字典键和来自dict的值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆