pythonpython-3.xdictionary

Appending values to a list within a dictionary


The following is my created dictionary testDict:

{'BTC': [23031.0897756201, 443936922524.46, 1], 'LTC': [89.6019345445, 6465505641.56, 2], 'NMC': [1.4363653274, 21166854.02, 3], 'TRC': [0.0180333433, 413601.88, 4']}

Im looking to append the following names to each list respectively:

Below is my code:

def symbol_and_price1(rawInfoList, testDict):
    # print(testDict)
    nameList = []
    for req in rawInfoList:
        name = req['data']['name']
        nameList.append(name)
    testDict['BTC'].append(nameList)
    print(testDict)

rawInfo()

Output:

{'BTC': [23031.0897756201, 443936922524.46, 1, ['Bitcoin', 'Litecoin', 'Namecoin', 'Terracoin']], 'LTC': [89.6019345445, 6465505641.56, 2], 'NMC': [1.4363653274, 21166854.02, 3], 'TRC': [0.0180333433, 413601.88, 4]}

It appends the whole list for the specified key (BTC); How can I make each key dynamic, and append the corresponding value to each key?

Desired output:

{'BTC': [23031.0897756201, 443936922524.46, 1, Bitcoin], 'LTC': [89.6019345445, 6465505641.56, 2, Litecoin], 'NMC': [1.4363653274, 21166854.02, 3, Namecoin]...etc}

Solution

  • You should modify each list separately. Replace the following line:

    testDict['BTC'].append(nameList)
    

    with this:

    for i, (key, value) in enumerate(testDict.items()):
        value.append(nameList[i])