【问题标题】:Passing multiple values from dictionary into method using loop使用循环将多个值从字典传递到方法中
【发布时间】:2021-02-05 12:36:15
【问题描述】:

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

这是我想写的,但它并没有按我的意愿工作,因为它每次只创建一个带有一个键/值的数据包

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
    },

 

制作更多通用以便于理解,希望对你有所帮助

Generic code

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,)
  

【问题讨论】:

标签: python arrays json for-loop arguments


【解决方案1】:

这个问题解决了我的问题:How to pass dictionary items as function arguments in 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,)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多