-3

I have two dicts as of below:

dict1 = {'name':'john', 'age':43}
dict2 = {'sex':'male', 'place':'southafrica'}

Note: dict2's keys and values can change all the time

How do we combine two dicts like this:

res = {'name':'john', 'sex':'male', 'place':'southafrica'}

I want to write this into a txt file with delimiter '|' like below"

name|sex|place
john|male|southafrica

How can we achieve this with python?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Walter White
  • 39
  • 1
  • 10
  • 1
    What happen to 'age' 43 ? – wim Oct 15 '18 at 20:41
  • Why isn't age printed? And possible duplicate of [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression) – clabe45 Oct 15 '18 at 20:41
  • Do you care if one of the original dictionaries gets modified? You can call `dict1.update(dict2)` to add dict2 to dict1. – Karl Oct 15 '18 at 20:41
  • we dont need dict1['age'] for this @wim – Walter White Oct 15 '18 at 20:43
  • There are two separate questions here; please ask a single question per post. The second part is solved with [`csv.DictWriter(outputfile, delimiter='|')`](https://docs.python.org/3/library/csv.html#csv.DictWriter). – Martijn Pieters Oct 15 '18 at 20:43
  • 2
    @WalterWhite: then make it explicit as to what is and what isn't needed. What are the rules of the combination? – Martijn Pieters Oct 15 '18 at 20:44

1 Answers1

1

Building from Karl's comment:

dict1 = {'name':'john', 'age':43}
dict2 = {'sex':'male', 'place':'southafrica'}

# combine the dicts
dict1.update(dict2)

# Get the keys
keys = dict1.keys()

# Get the values corresponding to each key in proper order
values = [dict1[key] for key in keys]

# Write to a file
fout = open('fileout.txt','w')
print('|'.join(map(str, keys)), file=fout)
print('|'.join(map(str, values)), file=fout)
fout.close()
killian95
  • 803
  • 6
  • 11