python - 使用循环将多个值从字典传递到方法中
问题描述
我有一个关于使用循环向方法添加字典键和值的问题
这就是我想写的,但它不能按我想要的方式工作,因为它每次只创建一个带有一个键/值的数据包
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,)
解决方案
这个问题解决了我的问题:如何在 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,)
推荐阅读
- javascript - 数据表不显示
- wpf - 如何正确地将图标或图像添加到 Mahapp DropDownButton 内的每个菜单项
- c++ - 以这种方式在运行时访问元组的性能成本
- html - 有没有办法为影子根元素定义 css
- python - 如何在python中设置由多处理创建的新进程的名称或标题?
- amazon-web-services - 安西布尔。创建不同的 ec2 实例错误:最小实例计数必须大于零
- django - 如何使用模型实例的一些参数初始化表单
- bash - .bash_profile 中意外标记“then”附近的语法错误
- php - 如何让分页与使用 ajax 和 PHP 的过滤器一起工作
- javascript - 将函数应用于函数(难以解释)