繁体   English   中英

Python 使用字典或列表作为用户输入

[英]Python using dictionary or list as user input

我使用最底部的字典来调用带有用户输入的函数。

我想使用字典、列表或任何其他解决方案让用户输入rds_cluster_name的值。 这是有问题的行DBClusterIdentifier = rds_cluster_name.input("RDS cluster name: ")

当我执行上述操作时,我收到错误AttributeError: 'dict' object has no attribute 'input'

所以我运行脚本并且必须从这里输入一个值funct_dict = {'start':start, 'stop':stop, 'status':status} ,如果调用了函数status ,则必须传递集群名称。

我可以在声明变量rds_cluster_name = input("RDS Cluster: ") ,它会起作用,但他们必须知道集群名称,我希望用户看到一个列表或类似的内容Choose cluster_name ('staging-cluster':1,'qa-cluster-1':2,'int1-cluster':3)并且他们只需输入与要使用的集群名称相对应的数字。

我怎样才能做到这一点?

rds_cluster_name = {'staging-cluster':1,'qa-cluster-1':2,'int1-cluster':3}

def status():
    rds_client = boto3.client('rds')
    response = rds_client.describe_db_clusters(
        DBClusterIdentifier = rds_cluster_name.input("RDS cluster name: "),
        MaxRecords=20,
    )
    status = response['DBClusters'][0]['Status']
    status = status.upper()
    print(f' RDS cluster "{rds_cluster_name}" is: {status}')

funct_dict = {'start':start, 'stop':stop, 'status':status}
if __name__ == "__main__":

    command = input("Input action: ")
try:
    funct_dict[command]()
except KeyError:
    print(f'Command "{command}" is unknown. Only values accepted are: start, stop or status')

我可能会出错,但我认为dict s 没有input属性。 您可能正在尝试根据输入获取字典键,在这种情况下:

DBClusterIdentifier = rds_cluster_name[input("RDS cluster name: ")]

这会将DBClusterIdentifier设置为rds_cluster_name["whatever they inputted"] (应该是staging-clusterqa-cluster-1int1-cluster ,分别将DBClusterIdentifier设置为123 )。

回答我自己

我已经设法完成了我需要的东西,代码与我最初想象的有点不同,但我并不感到惊讶,因为我正在学习 Python 并且一切对我来说都是新的:-)

之前我想调用rds_cluster_name的变量,现在我调用cluster_dict

如果向下滚动,您会发现这个cluster_dict = cluster_dict[x]['name']并且在该行是当变量加载用户从列表中选择的新值时。

学习这个我很开心,希望这能帮助别人,干杯。

# My dict variable with items numbered
#
cluster_dict = {
    1: {'name': 'staging-cluster'},
    2: {'name': 'qa-cluster-1'},
    3: {'name': 'int1-cluster'}
}
print("Cluster to be chosen")
# Printing out the content of the variable
#
for x, y in cluster_dict.items():
    print(x, ':', cluster_dict[x]['name'])

while True:
    print("\nSelect a Cluster:")
    # Right user input, all I needed
    #
    x = int(input())
    
    # And here, if it is right just "break" out of the while, if not go back to iterate
    #
    if x in cluster_dict.keys():
        x = int(x)
        print("\nYou have chosen: {0}".format(cluster_dict[x]['name']))
        print("\n")
        # At this point is where the variable is loaded with the value chosen by the user
        #
        cluster_dict = cluster_dict[x]['name']
        break
    
    else:
        print('\nNumber not in list, try again!')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM