【问题标题】:storage or overwrite a value to a specific key python存储或将值覆盖到特定键 python
【发布时间】:2021-01-12 18:59:27
【问题描述】:

我是 Python 编程的新手,目前有一个小问题。换句话说,我正在尝试制作一个输出 (print()),其中带有正确键的保存值(从输入中选择)将显示在终端中。

这是我已经写的。我希望它能帮助你理解我的问题:D

if request_filename in dictionary_main:
        new_mark = input('What is the new number which should be saved to the filename?: ')
        print('Your saved work: ' + str(request_filename) + 'Mark: ' + str(dictionary_main[request_filename]))
        print('---------Changes has been saved---------')

总而言之,我想将一个值保存到一个键中,然后我想在控制台中显示它们(键和值),例如:

“key is value”左右

提前感谢您的帮助! :)

【问题讨论】:

  • 如果您创建了一个minimal reproducible example 并简单、清晰地描述了您想要完成的工作,您的问题可能会更清楚。这里有很多不相关的代码,很难理解你的问题到底是什么。
  • 哦,好的,抱歉,我将更改问题并使其更易于理解
  • 现在好点了吗? LG
  • request_filenamedict 的类型,而不是str?我想知道代码示例是否可行。
  • request_filename = input('请输入文件名:') --> 应该是用户的输入。

标签: python dictionary input terminal output


【解决方案1】:

在 Python 中,您可以使用字典对象的键来操作字典对象。

例如:

BASKET = {
   'apple': 1,
   'banana': 2
}

print(f"There is {BASKET['apple']} apple in basket") # There is 1 apple in basket

# update banana's value
BASKET['banana'] = 1
print(f"There is {BASKET['banana']} banana in basket") # There is 1 banana in basket

【讨论】:

  • 非常感谢您的回答 Divik :) 但现在我想为 Key 添加一个值。我该怎么做?
  • @MartinLackner 您也可以像上面的代码一样使用str 作为密钥来创建密钥。就像BASKET['orange'] =2 将创建一个键orange 并将其值存储为2
  • 哦,我现在知道了……我想……我要测试一下。如果我还有问题,我可以回复你吗?
  • 当然。如果与此问题无关,您可以在 StackOverflow 中提出另一个问题。
  • 非常感谢您的帮助。现在代码按预期工作。祝你有一个愉快的夜晚,再见;) :D :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多