如何从输入中打印字典? [英] How to print Dictionary from Input?

查看:153
本文介绍了如何从输入中打印字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有几周学习Python的知识,所以请多多包涵.

I am only a few weeks into learning Python so please bear with me.

我已经创建了一组词典,我希望用户能够(通过Input)搜索一个词典的名称,然后搜索整个词典的Print.

I have created a set of dictionaries, and I would like the user to be able to search the name of one (via Input) and then Print the whole dictionary.

我可以看到问题出在哪里,当我输入Input时,它会将其分配给它自己的变量,然后将其调用给Print....那个变量名的字典?

I can see where the issue is, when I'm entering the Input it's assigning it to it's own variable, then calling that to Print... is there any way I can take the value and display the dictionary with that variable name?

DICT001 = {
     'MAP' : 'XXXX',
     'SSC'   : '0333',
     'Method': 'R',
     'Code1': 'S093733736',
     'Reg ID'  : '01'
}

DICT002 = {
     'MAP' : 'XXXX',
     'SSC'   : '0333',
     'Method': 'H',
     'Code1': 'B19SN99854',
     'Reg ID'  : 'S'
}

Search = input("Enter Dictionary to Search:")

print (Search)

我完全理解了为什么上面的代码根本不起作用,它只是打印我创建的搜索变量...但是,我似乎在任何地方都找不到解决此问题的方法.

I understand completely why the code above doesn't work at all, its just printing the Search Variable I've created... However I can't seem to find any work around for this anywhere.

任何帮助将不胜感激!

推荐答案

简短答案:

c = "DICT001"
tmp_dict = globals().get(c, None)
print(tmp_dict if tmp_dict else "There's no variable \"{}\"".format(c))

扩展答案:

是的,有几种方法可以通过其字符串名称来获取变量的值,但实际上通常需要它是错误代码的标记.

常规的存储方式,例如嵌套字典.

Regular way to store such as data will be nested dictionary.

示例:

dictionaries = {
    "DICT001": {
         'MAP' : 'XXXX',
         'SSC'   : '0333',
         'Method': 'R',
         'Code1': 'S093733736',
         'Reg ID'  : '01'
    },
    "DICT002": {
         'MAP' : 'XXXX',
         'SSC'   : '0333',
         'Method': 'H',
         'Code1': 'B19SN99854',
         'Reg ID'  : 'S'
    }
}

它可以避免搜索变量.您只需要按字典中的键即可获得价值.

It allows you to avoid searching for variable. You need just to get value by key in dictionary.

代码:

c = "DICT001"
tmp_dict = dictionaries.get(c, None)
print(tmp_dict if tmp_dict else "There's no key \"{}\"".format(c))

这篇关于如何从输入中打印字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆