【问题标题】:How to assign a name to a dictionary based on input from a user如何根据用户的输入为字典分配名称
【发布时间】:2020-12-30 02:11:51
【问题描述】:

我们如何为字典分配一个取自用户输入的名称并将该字典保存到一个 txt 文件中,以便我们可以通过它的名称搜索它并将输出打印给用户? 我现在在这里:

有什么想法吗?

import sys
import pathlib
'''Arg-V's should be in following order <app.py> <action> <nick_name> <name> <phone> <email>'''

if str(sys.argv[1]).lower == 'add':
    current = {'Name': sys.argv[3], 'Phone Number': sys.argv[4], 'Email': sys.argv[5]} 
    with open('contacts.txt', 'w') as f:
        f.write(current)

【问题讨论】:

  • 给字典命名是什么意思?
  • json.dump() 是保存字典等基本项目的好方法。另外,if 语句应该使用.lower(),而不是.lower
  • 我试图通过 sys.argv 从用户那里获取一个短语,然后将该值作为字典的名称
  • @JohnGordon 是一个初学者,我们将如何实现 Jason.dump 方法。
  • 您需要导入 json,在导入 sys 和 pathlib 时使用 json.dump

标签: python python-3.x python-3.8


【解决方案1】:

根据Naming Lists Using User Input

一个间接的答案是,正如其他几个用户告诉你的那样,你不想让用户选择你的变量名,你想使用一个列表字典,这样你就有了用户的所有列表在一个地方一起创建。

import json

name = input('name/s of dictionary/ies : ')


names = {}

name = name.split()

print(name)

for i in name:
    names[i]={}

print(names)

for i in names:
    print(i,'--------->', names[i])

for i in names:
    names[i] = '1'*len(i)
for i in names:
    with open(i+'.txt', 'w+') as file:
        file.write('prova : '+json.dumps(names[i]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2021-12-29
    • 2019-01-05
    相关资源
    最近更新 更多