Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list if it doesn't exist and add to list if it does

Say I have a dictionary that looks like this:

mappings = {"some_key": 3}

or it could look like this:

mappings = {"some_key": [4,5,6]}

Say I have a value 100 and a key of "some_key" in this function:

def add_to_mappings(key, value):
    if key in mappings:
        mappings[key] = ?

and I either want to add to the list if it exists or create one if it does not. At the end, I want my mappings to look like either:

   mappings = {"some_key": [3, 100]}

or

   mappings = {"some_key": [4,5,6,100]}
like image 309
Jwan622 Avatar asked Jan 01 '23 10:01

Jwan622


2 Answers

Without defaultdict:

mappings = dict()

def add_to_mappings(key, value):
  try:
    mappings[key].append(100)
  except KeyError:
    mappings[key] = [100]

With defaultdict:

from collections import defaultdict

mappings = defaultdict(list)

def add_to_mappings(key, value):
  mappings[key].append(value)

Edit: I misunderstood the original requirements, to take an item if it already existed and create a list out of it and the new item, then the first example could be changed to this:

mappings = dict(foo=3)

def add_to_mappings(key, value):
  try:
    mappings[key].append(100)
  except KeyError:
    mappings[key] = [100]
  except AttributeError:
    mappings[key] = [mappings[key], value]

add_to_mappings("foo", 5)
# mappings ==> { "foo": [3, 5] }
like image 156
ParkerD Avatar answered Feb 04 '23 03:02

ParkerD


You check if something is a list with isinstance(x, list). You can extract existing values from a dictionary and replace the value with simple assignment. So:

def add_to_mappings(d, key, value): # Remember to pass in the dict too!
    if key in d:
        # The value is present
        v = d[k]
        if isinstance(v, list):
            # Already a list: just append to it
            v.append(value)
        else:
            # Not a list: make a new list
            d[k] = [v, value]
    else:
        # Not present at all: make a new list
        d[key] = [value]
like image 37
Mad Physicist Avatar answered Feb 04 '23 05:02

Mad Physicist