我有一个词典
my_dict =
{ '123@com' : [ { 'event': 'event1', 'oldval' = 1, 'newval = 2}, { 'event': 'event2', 'oldval' = 11, 'newval': 22}, { 'event': 'event3', 'oldval' = 33, 'newval': 44}]
{'1234@com' : { 'event1': 'oldval': 45, 'newval': 66},
{'12345@com': [ {'event':'event2', 'oldval': 77, 'newval': 99}, { 'event': 'event3', 'oldval': '99', 'newval': 100'}]
所以基本上我的目标是建立一个列表
[ ['123@com', (2,1,True), (22,11, True), (44,33,True)], ['1234@com', (66,45,True), ('','',False),('','',False)], ['12345@com', ('',''False), (99,77,True), (100,99)]]
所以我的目标是在事件发生变化时捕获值并获取值并标记为true。
所以我写的代码如下:
for key,value in my_dict.items():
if str(my_dict).find('event1') >- 1 or str(my_dict).find('even2') > 1 or str(my_dict).find('event3') > -1:
tmp_list = []
tmp_list.append(key)
if type(value) is dict:
if value['event'] == 'event1':
@ get all the value and append to tmp_list
if value['event'] == 'event2':
@ do the same thing as above
else:
for val in value:
if val['name'] == 'event':
@ do the same stuff.
@do the same stuff again for rest of event.
所以基本上我可以通过遵循上面的代码模式来实现我的目标。
所以任何人都可以帮助我更好地编码,我会非常感激。 我不喜欢我编码的方式。
由于
答案 0 :(得分:0)
拥有像['123@com', (2,1,True), (22,11, True), (44,33,True)]
这样的异构列表是代码气味。它几乎总是意味着你试图用简单的数据类型做太多,并且可能通过实际使用类来提供更好的服务。假设python 2.x:
class Event(object):
def __init__(self, event, oldval, newval):
self.event = event
self.oldval = oldval
self.newval = newval
class EventThing(object):
def __init__(self, key, event_list):
self.key = key
self.event_list = [Event(**e) for e in event_list]
def produceCondensedList(self):
return [(e.oldval, e.newval, True) for e in self.event_list]
thing_list = [EventThing(key, event_list) for key, event_list in my_dict.items()]
它与您给出的示例不完全相同,但如果不了解您的确切用例,则很难提出准确的答案。以上应该足以让你开始。
答案 1 :(得分:0)
这是我能想到编码的最好方法。
def value_finder(val):
return lambda ev,li: next((di[val] for di in li if di['event']==ev),'')
def event_finder(ev,li):
return any(di['event']==ev for di in li)
def tuple_return(ev,li,nv,ov):
return (nv(ev,li),ov(ev,li),event_finder(ev,li))
def main(my_dict):
lis = []
nv = value_finder('newval')
ov = value_finder('oldval')
events = ['event1','event2','event3']
for key,value in my_dict.items():
temp_list = [key]
temp_list += [tuple_return(ev,value) for ev in events]
lis.append(temp_list)
print lis
my_dict = {'123@com':[{'event':'event1','oldval':1,'newval':2},
{'event':'event2','oldval':11,'newval':22},
{'event':'event3','oldval':33,'newval':44}],
'1234@com':[{'event':'event1','oldval':45,'newval':66}],
'12345@com':[{'event':'event2','oldval': 77,'newval': 99},
{'event':'event3','oldval':'99','newval':100}]}
main(my_dict)