[英]Comparing keys of a dictionary in Python and extracting corresponding values
I have two dictionaries:-我有两本字典:-
dict_1 = {'a': ["['b','c','d','e']"],'b': ["['a','c','d','e']"],'p': ["['q','r','s']"]}
dict_2 = {'a': ["['x','y','z','n']"],'b': ["['u','v','w','x','y','z','n']"]}
I want to extract value of all the key for which exit in both dictionaries, such that at time I can get only one value of corresponding key at time from a dictionary.我想提取两个字典中退出的所有键的值,这样我一次只能从字典中获取相应键的一个值。
Expected output预期输出
kindly help me to get the output.请帮助我获得输出。
I don't know what's a dataframe.我不知道什么是数据框。 Here is the code and sample output:这是代码和示例输出:
dict_one = {1: [1, 2, 3, 4]}
dict_two = {1: [7, 8, 9, 10]}
all_keys = set(dict_one).union(set(dict_two))
rows = []
for key in all_keys:
dict_one_values = []
if key in dict_one:
dict_one_values = dict_one[key]
dict_two_values = []
if key in dict_two:
dict_two_values = dict_two[key]
for i in range(min(len(dict_one_values), len(dict_two_values))):
rows.append([key, dict_one_values[i], dict_two_values[i]])
for row in rows:
print(*row)
output:输出:
1 1 7
1 2 8
1 3 9
1 4 10
I will assume this input:我会假设这个输入:
dict_1 = {'a': ['b','c','d','e'],'b': ['a','c','d','e'],'p': ['q','r','s']}
dict_2 = {'a': ['x','y','z','n'],'b': ['u','v','w','x','y','z','n']}
if not you can easily obtain it with dict_i = {k: literal_eval(v) for k,v in dict_i.items()}
如果不是,您可以使用dict_i = {k: literal_eval(v) for k,v in dict_i.items()}
轻松获得它
You can use a comprehension to select the expected data, and use it to build your dataframe:您可以使用理解来选择预期的数据,并使用它来构建您的数据框:
data = [(k, v1, v2) for k in dict_1 if k in dict_2
for v1, v2 in zip(dict_1[k], dict_2[k])]
df = pd.DataFrame(data)
it gives:它给:
0 1 2
0 a b x
1 a c y
2 a d z
3 a e n
4 b a u
5 b c v
6 b d w
7 b e x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.