简体   繁体   中英

Python function to append a list to a key in a dictionary

I have a dictionary with keys. The corresponding value of the key can be a list / dictionary / string.

If it is a list, the objective is : append another list( which will be acquired from another dictionary key) to the existing list against the key.

If it is a string / dict, the objective is : overwrite the new string / dictionary on it.

Any advice on how to achieve it ?

EDIT :

Sorry for not providing an example.

Suppose I have dictionary A as

{
  "names" :  ["John","Tyler","Peter"],
  "Institution" :{
                   "name" : "St. John's Business School",
                   "address" : "34 Janson Drive"
                  }
}

and B as

{
 "names" : ["Alice","Joanna"],
 "class" :  "Economics",
 "Institution" : {
                   "name" : "St. Mary's Republic",
                   "address" : "88, Weston Road"
                  }
}

Now what I want to achieve is:

I will iterate through B,

if the key is not present in A (like "class"), I will add it to A.

if it is present and it's value is a string/dict, I will replace the value in A with the value in B (as done with "Institution")

If it is present and it's value is a list, I will append the list in B to the list in A. (as done in "names")

So after my function is done, the final dictionary would look like :

{
  "names" : ["John","Tyler","Peter","Alice","Joanna"]
  "class" : "Economics",
  "Institution" : {
                       "name" : "St. Mary's Republic",
                       "address" : "88, Weston Road"
                      }
}

I have managed to get the string / dict condition correct. But I am not able to append to the existing list.

Any suggestion ? Thanks in advance

Is there any code you could show us to see what exactly is needed?

If it's just going to be appending a list as a value to an existing or new key in a dict this might work:

myDict["movies"].append(['Jurassic Park 4'])

That may work, but again, is there something specific you are trying to accomplish with a dict/list comprehension.

def update_dict(current_dict: dict, key: str, value: object) -> None:
    """
    Update existing dictionary with the following rules:
        - If the corresponding value of the key is a list; then append the value
        - If the corresponding value of the key is a string or dict; then overwrite the old value
    :param current_dict: current dictionary (e.q dictionary with keys)
    :param key: the key you want to process
    :param value: the value you want to add tot the specific key
    :return: None
    """
    if key not in current_dict:
        current_dict[key] = value # If the key doesn't exist, add it. However, you can raise a Exception if you want

    elif type(value) not in [str, list, dict]:
        raise ValueError("Invalid value type \"{val_type}\"".format(val_type=type(value)))

    elif isinstance(value, list):
        current_dict[key].append(value)

    else:
        current_dict[key] = value

if __name__ == '__main__':
    d = {"a": "", "b": [1, 2], "c": {"x": 1, "y": 2, "z": 3}}
    update_dict(d, 'a', 'New string')
    update_dict(d, 'b', ['a', 'b'])
    update_dict(d, 'c', "This was a dictionary")

    print(d)

OUTPUT

{'a': 'New string', 'b': [1, 2, ['a', 'b']], 'c': 'This was a dictionary'}

while iterating over your dictionary, you can use isinstance and type functions to check if it is a list, dictionary or a string and then you can perform your operations based on their type.

Example code

 d = {'a':[1,2,3], 'b':{'k1': 'v1', 'k2':'v2'}, 'c':'string1'}

l2 = [4,5,6]
d2 = {'k3':'v3', 'k4':'v4'}
c2 = 'string2'
for i in d:
    if type(d[i]) is list:
        d[i].append(l2)
    elif type(d[i]) is dict:
        d[i] = d2
    elif type(d[i]) is str:
        d[i] = c2
    else:
        pass

I hope I get what you want. You could use if else

data = {'a','b','c'}
another_list = {'b','d','e'}

if type(data) is list: 
    data.append(another_list)
elif type(data) is dict:
    data.append(overwrite_the_new_string
else: 
    print("your object is not a list/dict") 

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