根据下面列出的几个假设,我构建了一个自定义类来满足您的要求:
- 输入始终以括号
() 开头和结尾。
- 输入只能包含
""(空字符串)或"()"(空括号)或"(id=336346860, name='Western Australia', slug='western-australia', has_public_page=True, lat=-26.0, lng=121.0)"等实际值。
- 值将仅在 python 支持的
str、bool、int、float 中。
- 键值对始终由
= 分隔。
-
,(逗号)不是价值的一部分。 (即,逗号不存在于值中的任何位置
如果上述任何一个假设被打破,该类可能无法按预期工作
代码如下:
from typing import Optional
class MyDict:
def setRawElements(self):
"""Create a list by splitting the given string"""
# Assumption #5
# If there is any comma in the value, then the split may be inconsistent
self.raw_elements = self.string.split(", ")
def splitKeyValuePairs(self):
"""Split into key value pairs and create a internal dictionary"""
for elem in self.raw_elements:
# Assumption #4
# If the key and the value is not seperated by '=', then the split may be inconsistent
key, value = elem.split("=")
self.dictionary[key] = value
def setKeyTypes(self):
"""Type conversion"""
for key, value in self.dictionary.items():
# Assumption #3
# Value must be one among (bool, str, float, int)
if value in ["True", "False"]:
# check if the value is a boolean [True, False]
type_ = bool
elif value and value[0] == value[-1] == "'":
# check if the value is a str object
self.dictionary[key] = self.dictionary[key][1:-1]
# we need not convert a str to str, so we can skip the conversion part
continue
elif "." in value:
# float values will have two parts, integer and fraction seperated by a period
type_ = float
else:
# if above mentioned cases are not matched, ww assume that the type is int
type_ = int
# type conversion from str to excpected type
self.dictionary[key] = type_(self.dictionary[key])
def parse(self, string):
self.dictionary = {}
self.string = string
if string and string[1:-1]:
# Assumption #1 and #2
# If string is not empty and not just empty parenthesis
self.string = self.string[1:-1] # remove parenthesis from start and end
self.setRawElements()
self.splitKeyValuePairs()
self.setKeyTypes()
return self.dictionary
def __new__(cls, string: str) -> Optional[dict]:
"""Calling a class will return parsed dictionary"""
return super().__new__(cls).parse(string)
要使用该类,请参考以下代码:
fileOutput = "(id=336346860, name='Western Australia', slug='western-australia', has_public_page=True, lat=-26.0, lng=121.0)"
x = MyDict(fileOutput)
print(x)
下面是输出:
{'id': 336346860, 'name': 'Western Australia', 'slug': 'western-australia', 'has_public_page': True, 'lat': -26.0, 'lng': 121.0}
要检查值的类型,请参考以下代码:
for key, value in x.items():
print(key, value, type(value), sep=" - ")
输出:
id - 336346860 - <class 'int'>
name - Western Australia - <class 'str'>
slug - western-australia - <class 'str'>
has_public_page - True - <class 'bool'>
lat - -26.0 - <class 'float'>
lng - 121.0 - <class 'float'>