簡體   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