简体   繁体   English

如何将相同键的值转换为列表

[英]how to convert values of identical keys to list

unfortunately i have a big dictionary having many identical keys in it, and python not allows identical keys and prints only the last occurrence, now the solution i found is to changes values of identical keys to list or tuple.but i am not able to find a automatic way to do so.also i want to remain the order of values in list as i tried to mention it in example dictionary below. 不幸的是,我有一本很大的字典,里面有许多相同的键,而python不允许相同的键,并且只打印最后一次出现的键,现在我发现的解决方案是将相同键的值更改为list或tuple。但是我找不到一种自动的方法。我也想保留列表中值的顺序,因为我尝试在下面的示例字典中提及它。 my current dictionary looks like this: 我当前的字典看起来像这样:

dic = {
'a' : 2,
'a' : 1,
'b' : 2,
'a' : 4,
'a' : 3,
'b' : 1,
'b' : 2,
'c': 1
  }

now according to solution it should be converted to like this: 现在根据解决方案应将其转换为:

dic = {
'a' : [2,1,4,3],
'b' : [2,1,2],
'c': 1
  }

Thanks in advance. 提前致谢。

You need to first probe whether the dictionary already contains the key for which you're attempting to add a new value. 您需要首先探查字典是否已经包含要为其添加新值的键。 Once you've determined if the key already exists, you can then check whether the returned value is a single number, or a list of numbers and act accordingly. 确定键是否已存在后,可以检查返回的值是单个数字还是数字列表,并采取相应的措施。

In pseudocode: 用伪代码:

# Get current value associated with new key in dict.
# If returned value is None, add new value for key in question.
# Else If returned value is a list, append new value to list, store list for key in question
# Else, returned value was a single number; create a list of returned value and new value. Store list for key in question.

A solution in Python: Python解决方案:

class DictUtil(object):
    """ A utility class that automates handling of key collisions for a dictionary object. """

    @staticmethod
    def add_to_dict(dict, new_key, new_value):
        # Get whatever currently exists within the dictionary for the given key.
        value_in_dict = dict.get(new_key)

        # If the value for the given key is None, there is no current entry, so we can add the new value.
        if value_in_dict is None:
            dict[new_key] =  new_value

        # If the value for a given key returned a list, append new value to list and re-store in dict.
        elif type(value_in_dict) in [list, tuple]:
            dict[new_key].append(new_value)

        # Otherwise, the get returned a single item. Make a list of the returned value and the new value and re-store.
        else:
            dict[new_key] = [value_in_dict, new_value]

def main():
    """ Entry point for an example script to demonstrate Dictutil functionality. """
    dict = {}

    # Populating values in dict using Dictutil method: add_to_dict:
    DictUtil.add_to_dict(dict, 'a', 2)
    DictUtil.add_to_dict(dict, 'a', 1)
    DictUtil.add_to_dict(dict, 'b', 2)
    DictUtil.add_to_dict(dict, 'a', 4)
    DictUtil.add_to_dict(dict, 'a', 3)
    DictUtil. add_to_dict(dict, 'b', 1)
    DictUtil.add_to_dict(dict, 'b', 2)
    DictUtil.add_to_dict(dict, 'c', 1)

    # Printing dictionary contents
    for key, value in dict.iteritems():
        print 'Key: %s \t Value: %s' % (key, value)


if __name__ == '__main__':
    main()

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

相关问题 当键的值是列表列表时,如何将字典转换为 dataframe? - How to convert dictionary to dataframe when values of keys are list of list? 如何在两个词典中映射相同的项目并生成其相应键的值列表 - How to map identical items in two dictionaries and produce a list of values of their corresponding keys 将具有相同键的字典添加到列表中而不覆盖 Python 中的值 - Add dicts with identical keys to list without overwriting values in Python 将具有相同键但不同值的字典拆分到不同字典的列表 - Split list of dictionaries with identical keys but different values to different dictionaries 如何将列表转换为字典,其中某些键缺少其值? - How to convert a list to dictionary where some keys are missing their values? 如何将字典转换为按其值排序的键列表? - How to convert a dictionary into a list of its keys sorted by its values? 如何将列表项转换为默认值为 0 的字典键? - How to convert list items to dictionary keys with 0 as default values? 如何将字典转换为键列表,并由值给出重复计数? - How to convert a dictionary to a list of keys, with repeat counts given by the values? 将字典(带有键和值列表)转换为字典列表 - To convert a dict (with list of keys and values) into list of dict 将键列表和值列表转换为字典 - Convert list of keys and list of values to a dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM