简体   繁体   English

将随机键和值的列表转换为字典

[英]Convert a list of random keys and values to a dictonary

Suppose keys are represents by k n and values are represented by v n .假设键由 k n表示,值由 v n表示。

I have a list of keys and values like my_list_1 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k4,v10]我有一个键和值列表,例如my_list_1 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k4,v10]

Keys can be in repeated too in the list like my_list_2 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k2,v10]键也可以在列表中重复,例如my_list_2 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k2,v10]

All the values which are followed by a particular key belongs to that key.特定键后面的所有值都属于该键。 For instance in my_list_1;例如在 my_list_1; v1,v2,v3 belongs to k1; v1,v2,v3 属于 k1; v4,v5 belongs to k2; v4,v5 属于 k2; v6,v7,v8,v9 belongs to k3 and v10 belongs to k4. v6,v7,v8,v9 属于 k3,v10 属于 k4。 Therefore final dictionary would look like-因此最终的字典看起来像 -

{
   k1: [v1,v2,v3] ,
   k2: [v4,v5] ,
   k3: [v6,v7,v8,v9],
   k4: [v10]
}

Similarly in case of my_list_2 it would be:同样,在 my_list_2 的情况下,它将是:

{
   k1: [v1,v2,v3] ,
   k2: [v4,v5,v10] ,
   k3: [v6,v7,v8,v9]
}

How can I convert this kind of list in the required dictionary?如何在所需字典中转换这种列表?

Note: I already have functions to identify whether a particular item in list is a key or a value.注意:我已经有函数来识别列表中的特定项目是键还是值。 Let's call these functions as isKey() and isValue().我们将这些函数称为 isKey() 和 isValue()。

isKey() returns True if an item is a key else returns False isKey() 如果项目是键则返回 True 否则返回 False

isValue() returns True if an item is a value else returns False isValue() 如果项目是值则返回 True 否则返回 False

Maybe you could consider using a defaultdict :也许您可以考虑使用defaultdict

from collections import defaultdict
from pprint import PrettyPrinter

def is_key(s: str) -> bool:
    return s.startswith('k')

def is_value(s: str) -> bool:
    return s.startswith('v')

def convert_to_dict(my_list: list) -> dict:
    my_defaultdict = defaultdict(list)
    curr_key = None
    for s in my_list:
        if is_key(s):
            curr_key = s
        elif is_value(s):
            if curr_key is not None:
                my_defaultdict[curr_key].append(s)
    return dict(my_defaultdict)

my_list_1 = ['k1', 'v1', 'v2', 'v3', 'k2', 'v4', 'v5', 'k3', 'v6', 'v7', 'v8', 'v9', 'k4', 'v10']
my_dict_1 = convert_to_dict(my_list_1)
print("my_dict_1:")
PrettyPrinter().pprint(my_dict_1)

my_list_2 = ['k1', 'v1', 'v2', 'v3', 'k2', 'v4', 'v5', 'k3', 'v6', 'v7', 'v8', 'v9', 'k2', 'v10']
my_dict_2 = convert_to_dict(my_list_2)
print("\nmy_dict_2:")
PrettyPrinter().pprint(my_dict_2)

Output: Output:

my_dict_1:
{'k1': ['v1', 'v2', 'v3'],
 'k2': ['v4', 'v5'],
 'k3': ['v6', 'v7', 'v8', 'v9'],
 'k4': ['v10']}

my_dict_2:
{'k1': ['v1', 'v2', 'v3'],
 'k2': ['v4', 'v5', 'v10'],
 'k3': ['v6', 'v7', 'v8', 'v9']}

Not sure if this can be done in a more pythonic way, but here is a loop that ought to do it.不确定这是否可以以更 Pythonic 的方式完成,但这里有一个应该这样做的循环。 This assumes that a key will always directly precede all of its items and all of its items precede the next key.这假设一个键总是直接在它的所有项目之前,并且它的所有项目都在下一个键之前。

def my_list_to_dict(my_list):
    my_dict = {}
    my_key = None
    my_values = []
    for item in my_list:
        if isKey(item):
            if my_key != None:
                my_dict[my_key] = my_values
            my_key = item
            my_values = []
        elif isValue(item):
            my_values.append(item)
    return my_dict

You could create a function like this one:您可以像这样创建一个 function:

def to_dict(items):
    dictionary = {}
    current_key = None

    for item in items:
        if isKey(item):
            current_key = item
        elif current_key:
            if current_key in dictionary:
                dictionary[current_key].append(item)
            else:
                dictionary[current_key] = [item]

    return dictionary

And then call it like this:然后这样称呼它:

dictionary_1 = to_dict(my_list_1)
dictionary_2 = to_dict(my_list_2)

You can use a dictionary and add each element to the dictionary using a loop while keeping track of the current key.您可以使用字典并使用循环将每个元素添加到字典中,同时跟踪当前键。

def to_dictionary(my_list):
    output = {}
    current_key = None
    for item in my_list:
        if isKey(item):
            current_key = item
        elif isValue(item):
            output[current_key] = output.get(current_key, []) + [item]
    return output

print(to_dictionary(my_list_1))
{'k1': ['v1', 'v2', 'v3'],
 'k2': ['v4', 'v5'],
 'k3': ['v6', 'v7', 'v8', 'v9'],
 'k4': ['v10']}

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

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