I have the following 5 dictionaries:
d1 = {'a': 1, 'b': 2}
d2 = {'b': 10, 'c': 11}
d3 = {'e': 13, 'f': 15}
d4 = {'g': 101, 'h': 111}
d5 = {'i': 10, 'j': 11}
I would like to merge these five dictionaries and save as a txt file. The output should look like the following:
{{'a': 1, 'b': 2}, {'b': 10, 'c': 11}, {'e': 13, 'f': 15}, {'g': 101, 'h': 111}, {'i': 10, 'j': 11}}
or
{'a': 1, 'b': 2, 'b': 10, 'c': 11, 'e': 13, 'f': 15, 'g': 101, 'h': 111, 'i': 10, 'j': 11}
What I tried so far?
d = {**d1, **d2, **d3, **d4, **d5}
df = pd.DataFrame.from_dict(d, orient='index')
df.to_csv('output.txt')
This doesn't merge and save the output properly. How can I achieve that?
You don't need pandas for file handling (for this problem at least).
d = {**d1, **d2, **d3, **d4, **d5}
merges your dictionaries properly. To save this data as txt file, you only need python file handling:
with open('file.txt', 'w') as file:
# first convert dictionary to string
file.write(str(d))
Content of file.txt:
{'a': 1, 'b': 10, 'c': 11, 'e': 13, 'f': 15, 'g': 101, 'h': 111, 'i': 10, 'j': 11}
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.