2013-07-18 62 views
0
group1= [ { 
       'Name': 'C21114', 
       'Description': '', 
       'num': '12321114', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       '\xef\xbb\xbfUser_ID': 'C21114', 
       'Password': '*SECRET*', 
      }, 
      { 
       'Name': 'Mahes', 
       'Description': '', 
       'num': '1026', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       '\xef\xbb\xbfUser_ID': 'Mahi', 
       'Password': '*SECRET*', 
      }, 
      { 
       'Name': 'pri', 
       'Description': '', 
       'num': '1027', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       '\xef\xbb\xbfUser_ID': 'priya', 
       'Password': '*SECRET*', 
      }] 
group2= [{ 
       'Name': 'C21114', 
       'Description': '', 
       'num': '12321114', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       'User_ID': 'C21114', 
       'Password': '*SECRET*', 
      }, 
      { 
       'Name': 'Mahes', 
       'Description': '', 
       'num': '1026', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       'User_ID': 'Mahi', 
       'Password': '*SECRET*', 
      }, 
      { 
       'Name': 'pri', 
       'Description': '', 
       'num': '1027', 
       'working': 'true', 
       'belongs': 'Default', 
       'Expiry_Date': '', 
       'User_ID': 'priya', 
       'Password': '*SECRET*', 
      }] 

需要比较group1和group2的几个键是否相同。 group1和group2在很多词典中都有列出。我只需要比较几个键与其在group1和group2之间的值。用一个例子说明。例子:来自group1和group2的keys_to_compare = {'name','num',working}。使用列表中的键共同映射两个字典值

+2

欢迎来到StackOverflow。您发布的帖子很有可能会获得更多回复,如果您发布您的尝试 – inspectorG4dget

回答

0

这应该做你需要做的

key_to_compare = ['Name', 'num', 'working'] 
for key in key_to_compare: 
    for d1 in group1: 
     for d2 in group2: 
      if d1[key] == d2[key]: 
       print "same values for %s %s %s" % (key, d1[key], d2[key]) 

更改一下if语句做你喜欢什么具有相同值的元素。

+0

谢谢,用这个来完成我的事情。 – user2558589

0

我不得不对你想要的输出做出假设。我创建了一个列表清单。最内层的列表是索引(group1然后是group2)匹配的一部分。这是代码:

keys_to_compare = ['Name','num','working'] 
matches = [] 
for idx1 in range(len(group1)): 
    ref1 = group1[idx1] 
    found = False 
    for idx2 in range(len(group2)): 
     ref2 = group2[idx2] 
     found = True 
     for key in keys_to_compare: 
      if ref1[key] != ref2[key]: 
       found = False 
     if found: 
      matches.append([idx1,idx2]) 
      break 
    if found: continue 
print 'matches=%r' % (matches) 

结果:

matches=[[0, 0], [1, 1], [2, 2]] 
+0

谢谢你的工作,因为我需要 – user2558589

0

实现为功能,这应该给你想要的东西:

def compare(key): 
    g1 = [] 
    g2 = [] 
    for i in group1: 
     g1.append(i[key]) 
    for j in group2: 
     g2.append(j[key]) 
    return g1 == g2 

的键名把,然后将其如果两组的值相同,则返回True,否则返回False。例如,要检查您的列表中的键,你会这样做:

keys_to_compare = ['Name','num','working'] 

for x in keys_to_compare: 
    print compare(x) 
+0

谢谢你按要求工作 – user2558589