Home > database >  How do I convert a list of entries into a dictionary and merge it with an already existing dictionar
How do I convert a list of entries into a dictionary and merge it with an already existing dictionar

Time:11-04

Given I have the following function:

add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))

This function is supposed to convert values ('GOOG', 130.00) into a dictionary in the format 'GOOG':130.00. On top, it is meant to append the already existing dictionaries with values that are not already included.

Upon trying the code I stumble upon the issue that I cannot transform the list into a dictionary:

def add_to_list(x,y):
    output=list(y)
    dict.output
    return output

    

    
add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))

CodePudding user response:

This may be a flawed interpretation of the challenge.

def add_to_list(x, y):
    assert isinstance(x, dict)
    assert isinstance(y, tuple)
    k, v = y
    x.setdefault(k, []).append(v)
    return x
print(add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00)))

Output:

{'GOOG': [100.21, 130.0]}

CodePudding user response:

def add_to_list(x,y):
    d={y[0]:y[1]}
    return d
add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))
{'GOOG': 130.0}
  • Related