英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论