There is a line like:

[{'insp': '4816'}, {'insp': '3252'}, {'insp': '7107'}, {'insp': '5948'}, {'insp': '5257'} , {'insp': '5916'}, {'insp': '1673'}, {'insp': '5503'}, {'insp': '6030'}, {'insp': '6439'} , {'insp': '7151'}, {'insp': '2411'}, {'insp': '2208'}, {'insp': '5010'}, {'insp': '9978'} , {'insp': '5613'}, {'insp': '2634'}, {'insp': '2308'}, {'insp': '4711'}, {'insp': '5050'} , {'insp': '7721'}]

How can I translate such a string into a list of dictionaries?

  • Where do you get such a string? - andreymal
  • The string is similar to the JSON format, you can parse it using the json.loads function. - m9_psy
  • @andreymal awkward serialization :) - faoxis
  • @ m9_psy sobsna the problem is that it is not json - andreymal
  • 2
    @faoxis and change the serialization to the skillful with this very json in any way?) - andreymal

1 answer 1

# s = "[{'insp': '4816'}, ... , {'insp': '7721'}]" - исходная строка s = s.replace('\'','') #убираем внутренние кавычки for x in re.findall("\w+: \d+", s): # шаблон - 'строка: число' key, value = x.split(': ') print(key, value) # собрать список словарей не получиться т.к. ключи должны быть уникальны 
  • You can list_of_dicts = ast.literal_eval(s) instead of string manipulations. But it is better to change the input format to json so that json.loads () would work. - jfs