Home > Blockchain >  How to search/append a list within a dictionary
How to search/append a list within a dictionary

Time:11-09

Say I have a dictionary comprised of integer keys, and a list of integers corresponding to each key.

myDict = {0:[1,2,3,4], 1:[1,2,3], 2:[3,4,5]}

How do I search the list in key 1 for the integer 4, and if it's not in the list append it so that 1:[1,2,3,4]

CodePudding user response:

Try this:

myDict = {0:[1,2,3,4], 1:[1,2,3], 2:[3,4,5]}

# Only if k exists in 'dict'. We append value for that specific key
def search_append(d, k, v):
    if (k in d) and (not v in d[k]):
        d[k].append(v)

search_append(myDict, 1, 4)
print(myDict)
{0: [1, 2, 3, 4], 1: [1, 2, 3, 4], 2: [3, 4, 5]}


# if k is not in 'dict' we create a key and append the value
def search_append_2(d, k, v):
    if not v in d.get(k, []):
        d.setdefault(k, []).append(v)
        

search_append_2(myDict, 3, 4)
print(myDict)
# {0: [1, 2, 3, 4], 1: [1, 2, 3], 2: [3, 4, 5], 3: [4]}
  • Related