简体   繁体   中英

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. 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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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