【问题标题】:Python dict call function as valuePython dict 调用函数作为值
【发布时间】:2013-08-10 20:42:00
【问题描述】:

我正在使用返回的 json 在 python 中创建一个字典。

我想成为shortuuid的值之一,所以我把一个函数作为值。 我希望调用该函数并将值替换为该函数返回的值。

这对吗?

        tvMSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime}
             for msgkey, subdict, instakey in (('profilePIC', 'user', 'profile_picture'),
                         ('userNAME', 'user', 'username'),
                         ('msgBODY', 'caption', 'text'),
                         ('mainCONTENT','images', 'standard_resolution',)
                         ('tvshowID', shortuuid.uuid())):



   this is the key/value in question:
            ('tvshowID', shortuuid.uuid())):

这是我得到的错误:

        TypeError: 'tuple' object is not callable

如果没有,我该如何让它工作?

【问题讨论】:

  • 它没有按原样工作吗?
  • 不,我得到这个错误.... TypeError: 'tuple' object is not callable
  • 这是正确的做法。但是,您正在遍历一个 3 元组列表,而最后一个只是一个 2 元组。

标签: python json function loops


【解决方案1】:

错误来自缺少逗号。行:

('mainCONTENT','images', 'standard_resolution',)

实际上应该是:

('mainCONTENT','images', 'standard_resolution'),

这就是您收到错误'tuple' object is not callable 的原因,您正在调用('any','tuple')('arguments')

【讨论】:

  • 不错的收获!修复了 2 个问题...错误并删除了代码
【解决方案2】:

感谢@ThierryJ 的提示。

  tvMSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime, 'tvshowID: shortuuid.uuid()}
         for msgkey, subdict, instakey in (('profilePIC', 'user', 'profile_picture'),
                     ('userNAME', 'user', 'username'),
                     ('msgBODY', 'caption', 'text'),
                     ('mainCONTENT','images', 'standard_resolution')):

无需进行任何迭代。 我只是将该调用从循环中取出并将其放入循环上方的变量中。

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 2022-06-17
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多