0

I am trying to replace single quotation marks with double quotation marks in a Python dictionary object so that it works in a shell command. Basically, my dictionary is of this format:

{'PatientID': 'S007', 'PatientName': 'BOND^JAMES', 'PatientBirthDate': 'November'}

and I want it to look like

{"PatientID": "S007", "PatientName": "BOND^JAMES", "PatientBirthDate": "November"}

I have tried using:

patient_dict.replace('\'', '\"')

Which outputs the error message:

AttributeError: 'dict' object has no attribute 'replace'

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Louise Cullen
  • 97
  • 1
  • 8
  • 5
    There are some fundamental misunderstandings here, but the quick answer would be `import json` and do `print(json.dumps(mydict))` – pault Jun 05 '19 at 18:04
  • 2
    The quotes aren't actually part of the dictionary. – Scott Hunter Jun 05 '19 at 18:04
  • 1
    Thank you @pault ! That worked. – Louise Cullen Jun 05 '19 at 18:14
  • @pault it seems like they are the same in essence, with small details being different. Furthermore, It feels like luck that json.dumps() solved my issue as it changed the single quotations to double quotations. However, I was wondering if you had any idea how to change other single digits in a dictionary, e.g. if each dictionary key had a '_' in it that I wanted to change to a '-'? – Louise Cullen Jun 05 '19 at 18:25
  • @LouiseCullen as ScottHunter said, the quotes are not actually in your dictionary. It's only how strings are represented in python when you print them. Checking the values of keys is a different problem- there isn't a `replace` method but it's still fairly straightforward. I suggest you look up dictionary comprehension and the following `dict` methods: `keys()`, `items()`, `values()` – pault Jun 05 '19 at 18:28

0 Answers0