0

This question is similar to this thread: Python dict how to create key or append an element to key?

I'm trying to create a lookup which looks like this:

mydict = {'firstkey': ['element1', 'element2', 'element3'],
      'secondkey': ['element4', 'element5', 'element6']}

If I use the solution on the thread linked above, there is a potential for error as 'element1' could be added to 'firstkey' more than once. Therefore I check the element doesn't already exist like so:

mydict = {}
for element in another_list:
    mydict[key] = mydict.get(key, [])
    if element not in mydict[key]:
        mydict[key].append(element)

Is there a faster way to do this?

Full code example:

mydict = {}
for a_string in list_of_strings:
    # find string in mongodb database. find_one returns a dictionary
    document = db.BingResults.find_one({"akey": a_string})
    # Loop through a list
    for record in document["key"]:
        a_new_string = my_function(record["anotherkey"])
        mydict[a_new_string] = mydict.get(a_new_string, [])
        if a_string not in mydict[a_new_string]:
            mydict[a_new_string].append(a_string)
Jack
  • 394
  • 1
  • 15

0 Answers0