Python在dict中使用%s来调用值

Wil*_*Mak 1 python dictionary

我们怎样才能使用类似下面的dict?

dict[%s] % variable
Run Code Online (Sandbox Code Playgroud)

对于那些对我要做的事情感兴趣的人,我有三个要点:

    dict_1 = {'a':'123', 'b':'234', 'c':'345'}
    dict_2 = {'d':'456', 'e':'567', 'f':'678'}
    dict_3 = {'a':'e', 'b':'d', 'c':'f'}
Run Code Online (Sandbox Code Playgroud)

我有一个功能,我需要输入以下内容:

    function(dict_1['a'], dict_2['e']) #according to dict_3 that 'a' is paired with 'e'.
Run Code Online (Sandbox Code Playgroud)

编辑:

我试图编写一个for循环来遍历所有的dicts并让它们根据dict_3将dict_1和dict_2对配对到函数中.看着你们回答后,我实际上不需要%s的东西.这就是你在早上没有喝咖啡时尝试编码的情况.

最后,这一切做了我想要的,谢谢大家!:

    for i in dict_1:
         results = function(dict_1[i],dict_2[dict_3[i]]
Run Code Online (Sandbox Code Playgroud)

Rob*_*ley 5

如果我收集的内容是正确的,那么你几乎已经赚了钱.你可以像这样写:

dict["%s" % variable]
Run Code Online (Sandbox Code Playgroud)

然而,一个问题是,如果你有类似的东西:

   d = {3 : 'hello'}
   my_key = 3
   d['%s' % my_key]
Run Code Online (Sandbox Code Playgroud)

那会失败的 KeyError

无论如何,它是一种迂回的方式来使用它.你可以写:

dict[otherdict['a']]
Run Code Online (Sandbox Code Playgroud)

  • 我知道.但他的问题是如何以这种方式写出来.所以我给他看了 (3认同)