Make a dictionary with duplicate keys in Python

后端 未结 7 1218
野的像风
野的像风 2020-11-22 00:37

I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of

7条回答
  •  天命终不由人
    2020-11-22 01:13

    I just posted an answer to a question that was subequently closed as a duplicate of this one (for good reasons I think), but I'm surprised to see that my proposed solution is not included in any of the answers here.

    Rather than using a defaultdict or messing around with membership tests or manual exception handling, you can easily append values onto lists within a dictionary using the setdefault method:

    results = {}                              # use a normal dictionary for our output
    for k, v in some_data:                    # the keys may be duplicates
        results.setdefault(k, []).append(v)   # magic happens here!
    

    This is a lot like using a defaultdict, but you don't need a special data type. When you call setdefault, it checks to see if the first argument (the key) is already in the dictionary. If doesn't find anything, it assigns the second argument (the default value, an empty list in this case) as a new value for the key. If the key does exist, nothing special is done (the default goes unused). In either case though, the value (whether old or new) gets returned, so we can unconditionally call append on it, knowing it should always be a list.

提交回复
热议问题