Zapier“运行Python代码”错误 - 解析字典问题

问题描述 投票:0回答:1

我刚刚学习如何编写 python,但我一直在使用 Zapier 开始自动化一些任务。 (也是第一次发海报,大家好!)

我有以下数据:

countries = [
    {"Country_Num": 1, "Country_Name": "United States"},
    {"Country_Num": 2, "Country_Name": "United Kingdom"},
    {"Country_Num": 3, "Country_Name": "Canada"},
    {"Country_Num": 4, "Country_Name": "Germany"},
    {"Country_Num": 5, "Country_Name": "France"},
    {"Country_Num": 6, "Country_Name": "Australia"},
    {"Country_Num": 7, "Country_Name": "Japan"},
    {"Country_Num": 8, "Country_Name": "Brazil"},
    {"Country_Num": 9, "Country_Name": "India"},
    {"Country_Num": 10, "Country_Name": "South Africa"}
]

我正在尝试将这些数据转换为 Zapier 中可用的内容,以便我可以将该数据添加到 GoogleSheet 中。

因此,我使用名为“在 Zapier 的代码中运行 Python”的 Zapier 步骤,它允许我将上面的输入数据分配为“国家/地区”

现在,我尝试使用代码将数据转换为两个输出,我可以使用以下脚本使用它们:

# Accessing the input data which is provided as 'countries'
countries_data = input_data['countries']

# Initializing lists to hold country numbers and names
country_nums = []
country_names = []

# Iterating over each country in the input data
for country in countries_data:
    # Appending the country number and name to their respective lists
    country_nums.append(country["Country_Nums"])
    country_names.append(country["Country_Names"])

# Preparing the output to include both lists
output = {'Country_Nums': country_nums, 'Country_Names': country_names}

return output

但是,每当我尝试测试代码时,都会收到以下错误:

无法在 Zapier 的 Code 中创建运行的 python 您的代码有错误!回溯(最近一次调用最后一次):文件“”,第 18 行,函数中类型错误:字符串索引必须是整数,而不是“str”

如有任何帮助,我们将不胜感激!!

python zapier
1个回答
0
投票

您在分配“Country_Nums”时似乎犯了一个拼写错误。它应该是“Country_Num”。由于该拼写错误,使用国家/地区数据作为countries_data 将代码作为基本 Python 文件运行会出现错误。

修复它意味着代码正常运行 - 当我将

output
打印到终端时,它会写入

{'Country_Num': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Country_Name': ['United States', 'United Kingdom', 'Canada', 'Germany', 'France', 
'Australia', 'Japan', 'Brazil', 'India', 'South Africa']}

希望这有帮助!由于我不使用 Zapier,所以我不确定问题是否会完全相同,但从你如何详细介绍 Zapier 的功能来看,应该非常相似。

固定代码:

# Accessing the input data which is provided as 'countries'
countries_data = input_data['countries']

# Initializing lists to hold country numbers and names
country_nums = []
country_names = []

# Iterating over each country in the input data
for country in countries_data:
    # Appending the country number and name to their respective lists
    country_nums.append(country["Country_Num"])
    country_names.append(country["Country_Name"])

# Preparing the output to include both lists
output = {'Country_Num': country_nums, 'Country_Name': country_names}

return output
© www.soinside.com 2019 - 2024. All rights reserved.