向字典中的列表添加数值

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

Appending values to a list within a dictionary

问题

  1. 期望输出:
  2. {'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:

  1. {'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:

  1. def symbol_and_price1(rawInfoList, testDict):
  2. # print(testDict)
  3. nameList = []
  4. for req in rawInfoList:
  5. name = req['data']['name']
  6. nameList.append(name)
  7. testDict['BTC'].append(nameList)
  8. print(testDict)
  9. rawInfo()

Output:

  1. {'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:

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

答案1

得分: 2

将以下行分别修改为:

  1. testDict['BTC'].append(nameList)

改为:

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

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

  1. testDict['BTC'].append(nameList)

with this:

  1. for i, (key, value) in enumerate(testDict.items()):
  2. 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:

确定