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()}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.