首页 > 解决方案 > 使用循环将多个值从字典传递到方法中

问题描述

我有一个关于使用循环向方法添加字典键和值的问题

这就是我想写的,但它不能按我想要的方式工作,因为它每次只创建一个带有一个键/值的数据包

for key in packetData:
    for name in packetData[key]:
        packets = Ether()/IP()/UDP()/createsPacket(key, name=packetData[key][name])
        print ("as name " + name + " \n as value " + str(packetData[key][name]))

而不是这样手动编写:

packets1 = Ether()/IP()/UDP()/createsPacket("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = Ether()/IP()/UDP()/createsPacket("72", PriceID = 123, Side = 12, MaxAmount = 123, MinAmount = 123, Price = 123000)

    json 然后在 python 中转换为字典,这是我要传入的数据

    {
    "65":{
        "UserID":"vcjazfan",
        "Password":"ejujwlhk",
        "SessionID":115,
        "ETX":192
    },
    "66":{
        "UserID":"dzmtrssy",
        "SessionID":35,
        "Reason":"zbwivjcv",
        "ETX":43
    },
     "72":{
        "InstrumentIndex":171,
        "PriceID":217,
        "Side":226,
        "MaxAmount":210,
        "MinAmount":219,
        "Price":47,
        "PriceProvider":207,
        "ETX":78
    },

 

通用以便于理解,希望对您有所帮助

通用代码

dictionary = {"65":{ "UserID":"vcjazfan", "Password":"ejujwlhk", "ETX":192} ,   "72":{ "InstrumentIndex":171,  "PriceID":217, } }


#This is what i was thinking to write but it doesn't work how i want because it creates a packet just with one key/value every time
for key in dictionary:
    for name in dictionary[key]:
        value=dictionary[key][name]
        packets = method(key, name=value) # in first iteration when key is 65  ,  name = "UserID" ,  value = "vcjazfan"
                                          # in second iteration when key is 65   ,  name = "Password" ,  value = "ejujwlhk"  


#Instead of writing this manually like that :

packets1 = method("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = method("72", InstrumentIndex = 123, PriceID = 12,)
  

标签: pythonarraysjsonfor-looparguments

解决方案


这个问题解决了我的问题:如何在 python 中将字典项作为函数参数传递?

solution to  my original code:
Allpackets= []
for key in packetData:
    Allpackets.append(packets/createsPacket(key, **packetData[key]))


Solution to generic one:

dictionary = {"65":{ "UserID":"vcjazfan", "Password":"ejujwlhk", "ETX":192} ,   "72":{ "InstrumentIndex":171,  "PriceID":217, } }

Allpackets = []
for key in dictionary:
    Allpackets.append( method(key, **dictionary))


#Instead of writing this manually like that :

packets1 = method("65", UserID = "name", Password = "pass123", ETX = 123)
packets2 = method("72", InstrumentIndex = 123, PriceID = 12,)

推荐阅读