如何访问字典中列表中的整个值,而不是单个字符?

How do access entire value inside list inside dictionary, instead of single character?

我是编码的新手,我曾尝试查找内容并重新阅读我的笔记,但我无法理解这一点。我正在尝试检索字典内列表中的各个值 (all_customers)。我尝试检索号码的示例:

print(f"Earnings from how many months they subscribed for = ${(all_customers['customer1'][0])}")

但是在索引时,它会检索单个字符(如上例中的 return 括号:[),而不是完整数字(如 151)。它应该更像是:如果我为第一个客户输入 25 表示 months_subscribed10 表示 ad_free_months5 表示 videos_on_demand_purchasesall_customers['customer1'] 应该 return [151, 20, 139.95] 我在上面尝试打印的示例应该是“他们订阅了多少个月的收入 = 151 美元”而不是“他们订阅了多少个月的收入”对于 = [".

def subscription_summary(months_subscribed, ad_free_months, video_on_demand_purchases):  

    #price based on months subscribed
    if int(months_subscribed) % 3 == 0:
        months_subscribed_price = int(months_subscribed)/3*18
    elif int(months_subscribed) > 3:
        months_subscribed_price = int(months_subscribed)%3*7 + int(months_subscribed)//3*18
    else:
        months_subscribed_price = int(months_subscribed)*7
        
    #price of ad free months
    ad_free_price = int(ad_free_months)*2

    #price of on demand purchases
    video_on_demand_purchases_price = int(video_on_demand_purchases)*27.99

    customer_earnings = [months_subscribed_price, ad_free_price, video_on_demand_purchases_price]

    return customer_earnings
#Loop through subscription summary 3 times, to return 3 lists of customers earnings and add them to a dictionary
all_customers={}

for i in range(3):
    months_subscribed = input("How many months would you like to purchase?: ")
    ad_free_months = input("How many ad-free months would you like to purchase?: ")
    video_on_demand_purchases = input("How many videos on Demand would you like to purchase?: ")

    #congregate individual customer info into list and run it through the function
    customer = [months_subscribed, ad_free_months, video_on_demand_purchases]

    indi_sub_sum = subscription_summary(customer[0], customer[1], customer[2])
    #congregate individual customers subscription summary lists into a dictionary
  
    all_customers[f"customer{i+1}"] = f"{indi_sub_sum}"

我希望这是一个好的问题!抱歉,我是新手:)

尝试打印出 all_customers 词典,您会发现问题所在:

>>> all_customers
{'customer1': '[32, 8, 83.97]', 'customer2': '[25, 6, 55.98]', 'customer3': '[18.0, 4, 27.99]'}

你所有的列表实际上都是字符串。那是因为这一行:

all_customers[f"customer{i+1}"] = f"{indi_sub_sum}"

您正在为其分配一个字符串而不是列表。将其更改为:

all_customers[f"customer{i+1}"] = indi_sub_sum

应该会帮你解决。