向字典中的列表添加数值

huangapple go评论70阅读模式
英文:

Appending values to a list within a dictionary

问题

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

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:

  • Bitcoin
  • Litecoin
  • Namecoin
  • Terracoin

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}

答案1

得分: 2

将以下行分别修改为:

testDict['BTC'].append(nameList)

改为:

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

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])

huangapple
  • 本文由 发表于 2023年2月16日 09:15:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定