字典拼图
Dictionary Puzzle
好的,所以...
我下面有一些不想合作的词典。
字典 "a" 表示存储在我们的 HR 数据库中的数据。
字典 "b" 表示存储在我们的 AS400 iSeries 数据中的数据。
注意:这些不是真实值
目标是使用至少 2 个字段将 "a" 中的键与 "b" 中的键匹配,同时仍然能够引用该键。
换句话说,在我匹配了 2 个值之后,我希望能够创建一个新的字典来匹配 a 的键和 b 的键:
match_dictionary[*key from a*] = (*key from b*)
a.pop(*key from a*)
b.pop(*key from b*)
代码如下:
import collections
a = {'ada123456' : ('123','adam','jones') , 'jus567890':('567','justin','brady') , 'mul345678':('345','muller','thomas')}
b = {'ADAMJ' : ('123','jones') , 'JBRADY':('justin','brady') , 'THOMASM':('345','muller','thomas')}
if [i for i in [(x[1],x[2]) for x in [a[c] for c in a.keys()]]] in [b[d] for d in b.keys()]:
print('Why won\'t this work?')
if ('justin','brady') in [b[d] for d in b.keys()]:
print('\nthis works though')
if ('justin','brady') in [(x[1],x[2]) for x in [a[c] for c in a.keys()]]:
print('\nthis too')
我把它作为列表的关键字,以防你有多个匹配项
new_dict = defaultdict(list)
for b_name, b_values in b.items():
for a_name, a_values in a.items():
intersect = set(a_values).intersection(set(b_values))
if len(intersect) >= 2:
new_dict[a_name].append(b_name)
但将其更改为
会很容易
new_dict[a_name] = b_name
如果你愿意。那么你就不需要默认的字典了。
这会产生:
defaultdict(list,
{'ada123456': ['ADAMJ'],
'jus567890': ['JBRADY'],
'mul345678': ['THOMASM']})
如果你想要一个正常的 dict
背面,只需将它包裹在 dict()
中
好的,所以... 我下面有一些不想合作的词典。 字典 "a" 表示存储在我们的 HR 数据库中的数据。 字典 "b" 表示存储在我们的 AS400 iSeries 数据中的数据。 注意:这些不是真实值 目标是使用至少 2 个字段将 "a" 中的键与 "b" 中的键匹配,同时仍然能够引用该键。
换句话说,在我匹配了 2 个值之后,我希望能够创建一个新的字典来匹配 a 的键和 b 的键:
match_dictionary[*key from a*] = (*key from b*)
a.pop(*key from a*)
b.pop(*key from b*)
代码如下:
import collections
a = {'ada123456' : ('123','adam','jones') , 'jus567890':('567','justin','brady') , 'mul345678':('345','muller','thomas')}
b = {'ADAMJ' : ('123','jones') , 'JBRADY':('justin','brady') , 'THOMASM':('345','muller','thomas')}
if [i for i in [(x[1],x[2]) for x in [a[c] for c in a.keys()]]] in [b[d] for d in b.keys()]:
print('Why won\'t this work?')
if ('justin','brady') in [b[d] for d in b.keys()]:
print('\nthis works though')
if ('justin','brady') in [(x[1],x[2]) for x in [a[c] for c in a.keys()]]:
print('\nthis too')
我把它作为列表的关键字,以防你有多个匹配项
new_dict = defaultdict(list)
for b_name, b_values in b.items():
for a_name, a_values in a.items():
intersect = set(a_values).intersection(set(b_values))
if len(intersect) >= 2:
new_dict[a_name].append(b_name)
但将其更改为
会很容易 new_dict[a_name] = b_name
如果你愿意。那么你就不需要默认的字典了。
这会产生:
defaultdict(list,
{'ada123456': ['ADAMJ'],
'jus567890': ['JBRADY'],
'mul345678': ['THOMASM']})
如果你想要一个正常的 dict
背面,只需将它包裹在 dict()