student
student

Reputation: 27

python code output problem in list and dictionary

I have written this code-

    travel_log = [
    {
      "country": "France",
      "visits": 12,
      "cities": ["Paris", "Lille", "Dijon"]
    },
    {
      "country": "Germany",
      "visits": 5,
      "cities": ["Berlin", "Hamburg", "Stuttgart"]
    },
    ]
    def add_new_country(c,v,citi):
      travel_log.append(f'"country":{c},"visits": {v},"cities": {citi}')

    add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
    print(travel_log)

I have attached the image of output Why am i getting \ in last element of list.

Upvotes: 0

Views: 63

Answers (2)

Der Achim
Der Achim

Reputation: 90

Seems you convert the array to an object. ["Moscow" ...] -> "cities": {"String rep of array"}

Therfore the array gets converted and so get get "String chars '" in the array elements.

Upvotes: 2

Cardstdani
Cardstdani

Reputation: 5223

You are appending an f string to your list of dictionaries, which is not the appropriate formatting that you have on other values of that list. You need to append a Python dict element to avoid problems with string representations like \ special charcaters:

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(c,v,citi):
  travel_log.append({"country":c,"visits":v,"cities": citi})

add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

Output:

[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']}, {'country': 'Russia', 'visits': 2, 'cities': ['Moscow', 'Saint Petersburg']}]

Upvotes: 6

Related Questions