首页 > 解决方案 > 如何用Python中字典中的值替换函数变量

问题描述

我正在尝试遍历下面的字典并将函数内的“字符串”变量替换为字典中的值,然后执行该函数。我正在考虑编写一个 for 循环,然后将函数包含在 for 循环中。请帮忙。

预期功能:

def my_function(fname):
    string = value  
    print(string + " Refsnes")

my_function("string")
 dict = {"kafka":[{
"value":"I am"},
{"value":"You are"},
{"value":"They are"}
]}

def my_function(fname):
    string = "I am"  
    print(string + " Refsnes")

my_function("string")

标签: python

解决方案


最好的办法是首先修改你的字典。现在“kafka”映射到所有具有相同密钥的字典列表,那么为什么要首先打扰并拥有一个密钥。所以你可以有一个像这样的字典:

dictionary = {"kafka": ["I am", "You are", "They are"]}

也不要调用变量dict,因为你会覆盖内置函数dict,使其无法使用。

然后,您还必须更改函数以实际使用该参数。

def my_function(string):
    print(string + " Refsnes")

现在,要遍历 dict 并打印具有所有值的函数,您有两个选项。

首先循环遍历字典中的列表并重复调用该函数:

for string in dictionary["kafka"]:
    my_function(string)

或者给你的函数一个列表,然后循环遍历函数中的列表。您的函数将如下所示:

def my_function(list_of_strings):
    for string in list_of_strings:
        print(string + " Refsnes")

# Call function with 
my_function(dictionary["kafka"])

推荐阅读