简体   繁体   English

从列表创建多个 Python 字典?

[英]Create Multiple Python Dictionaries from a List?

I am having a difficult time splitting an LDIF file with thousands of entries into multiple dictionaries.我很难将包含数千个条目的 LDIF 文件拆分为多个字典。 For example, my LDIF file looks like:例如,我的 LDIF 文件如下所示:

dn: value
ou: value
objectClass: value
entryUUID: value
creatorname: value
entryNNN: value
modifierName: value
modifyTimestamp: value

dn: value
ou: value
…
…
…

What I would like to do is separate lines starting with "dn:" and every line under into separate dictionaries.我想做的是以“dn:”开头的单独行,并将每一行放入单独的字典中。 For Example:例如:

ldap_core_record_1 = {'dn:': 'value', 'ou:': 'value',...}
ldap_core_record_2 = {'dn:': 'value', 'ou:': 'value',...}

Here's the code I have so far:这是我到目前为止的代码:

def parse_LDAP_Core_Schema():
    LDAP_CORE_LIST = []
    LDAP_CORE_DICT = {}
    LDAP_CORE_FILE = '/…/…/…/…/ldap_core_backup.ldif'      """This is the LDAP generated from slapcat"""
    with open(LDAP_CORE_FILE, 'r') as LDAP_CORE_OBJECT:
        LDAP_CORE_LIST = LDAP_CORE_OBJECT.readlines()
        for line in LDAP_CORE_LIST:
            if line.startswith("dn: "):

From there, I'm stumped.从那里,我被难住了。 I don't know how to properly splice a List as I've only been using Python for a short while.我不知道如何正确拼接 List,因为我只使用了一段时间的 Python。 I'm using Python 3.4.2 unfortunately.不幸的是,我正在使用 Python 3.4.2。

Something along this line.沿着这条线的东西。

def parse_LDAP_Core_Schema():
    LDAP_CORE_FILE = '/…/…/…/…/ldap_core_backup.ldif'      """This is the LDAP generated from slapcat"""
    results = []
    with open(LDAP_CORE_FILE, 'r') as LDAP_CORE_OBJECT:
        results = []
        for line in LDAP_CORE_OBJECT:
            key, value = line.strip().split(': ')
            if key == 'dn':  # add new element to list
                results.append({'dn': value})
            else:  # add new key: value to latest element of list
                results[-1][key] = value
    return results 

This will get you the output that you want:这将为您提供所需的输出:

file_path = '/…/…/…/…/ldap_core_backup.ldif'

with open(file_path) as file:
    records = []
    for line in file.readlines():
        line = line.replace('\n', '')
        if not line:  # skip empty lines
            continue
        key, value = line.split(': ')
        if key == 'dn':
            records.append({key: value})
        else:
            records[-1][key] = value

print(records)

>>> [{'dn': 'value', 'ou': 'value', 'objectClass': 'value', 'entryUUID': 'value', 'creatorname': 'value', 'entryNNN': 'value', 'modifierName': 'value', 'modifyTimestamp': 'value'}, {'dn': 'value', 'ou': 'value'}]

You're very close!你非常接近! Just need to populate your LDAP_CORE_LIST with results from the temp LDAP_CORE_DICT .只需要填入你的LDAP_CORE_LIST与临时结果LDAP_CORE_DICT

def parse_LDAP_Core_Schema():
    LDAP_CORE_LIST = []
    LDAP_CORE_DICT = {}
    LDAP_CORE_FILE = '/…/…/…/…/ldap_core_backup.ldif'   # LDAP generated from slapcat
    with open(LDAP_CORE_FILE, 'r') as LDAP_CORE_OBJECT:
        LDAP_CORE_LIST = LDAP_CORE_OBJECT.readlines()
        for line in LDAP_CORE_LIST:
            if line.startswith("dn: "):    # If new DN
                if LDAP_CORE_DICT:         # Push current dict into list
                    LDAP_CORE_LIST.append(LDAP_CORE_DICT)
                k, v = line.split(":", maxsplit=1)      # Split line at first colon
                LDAP_CORE_DICT = {k: v.strip()}         # Create object with first value
            else:                          # Not a new DN line
                try:
                    k, v = line.split(":", maxsplit=1)  # Split line at first colon
                    LDAP_CORE_DICT[k] = v.strip()       # Update object
                except ValueError:         # Ignore blank and malformatted lines
                    pass
        else: # After completing the loops, push final dict into list
            if LDAP_CORE_DICT:             # Push current dict into list
                LDAP_CORE_LIST.append(LDAP_CORE_DICT)

    print(LDAP_CORE_LIST)                  # [{'dn': 'value1', 'ou': 'value2', ...}, ...]
    return LDAP_CORE_LIST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM