如何将字典作为参数发送到python函数

时间:2018-04-06 08:00:24

标签: python python-2.7 dictionary

下面的代码不起作用,数据是字典&我想知道如何将它传递给函数

from google.cloud import pubsub;
subscriber = pubsub.SubscriberClient()
subscription_path = subscriber.subscription_path(<project_id>, 
<subscription_name>)
    def callback(message):
print(message.data)
subscriber.subscribe(subscription_path, callback=callback)

1 个答案:

答案 0 :(得分:2)

以下代码应该适合您:

def my_function(x={}):
    for i, j in x.iteritems():
        print (i)
        print (j)

data = {'a':1, 'b': 2, 'c': 3}
my_function(data)

<强>解释

  • 确保缩进正确。
  • 要迭代字典,请使用dict.iteritems(在Python 2.x中)或dict.items(在Python 3中)。
  • 如果您以这种方式迭代字典,则没有理由使用解包**运算符。
  • 了解使用Mutable Default Arguments
  • 的陷阱