gpt4 book ai didi

python - 将包含一项的列表转换为字典值中的项本身

转载 作者:行者123 更新时间:2023-12-05 01:52:10 25 4
gpt4 key购买 nike

例如,有一个键值对的字典,其中的值是具有不同“内容”的列表。有些列表只有一个元素。这些元素可以是不同类型的数据。

问题:将具有一个元素的列表类型键值转换为字典值中的元素本身的最有效方法是什么?

输入数据

{
"key1": ["text"],
"key2": ["text", "text"],
"key3": [{"key0": 0}],
"key4": [{"key0": 0, "key1": 1}],
"key5": [],
"key6": [[]],
"key7": [["text"]],
"key8": [[{"key0": 0}]]
}

预期输出数据

{
"key1": "text",
"key2": ["text", "text"],
"key3": {"key0": 0},
"key4": {"key0": 0, "key1": 1},
"key5": "",
"key6": "",
"key7": "text",
"key8": {"key0": 0}
}

我尝试过的

{k: v[0] for k, v in dct.items()}

带有问题和评论的我的代码输出

{
'key1': 'text',
'key2': 'text', <- ISSUE 1 should be ["text", "text"]
'key3': {'key0': 0},
'key4': {'key0': 0, 'key1': 1},
'key5': <- ISSUE 2 Raises ERROR "IndexError: list index out of range" which is quite expected, should be ""
'key6': [], <- ISSUE 3 should be ""
'key7': ['text'], <- ISSUE 4 should be "text"
'key8': [{'key0': 0}] <- ISSUE 5 should be {'key0': 0}
}

Input data 中的字典转换为 Expected output data 中的字典的最有效方法是什么?

最佳答案

为了解决这个问题,我专注于如何转换值:我创建了一个名为 delist 的函数来删除包含 1 个元素的列表:

def delist(value):
while isinstance(value, list) and len(value) == 1:
value = value[0]
if value == []:
value = ""
return value

希望逻辑很容易理解。要使用它:

data = {
"key1": ["text"],
"key2": ["text", "text"],
"key3": [{"key0": 0}],
"key4": [{"key0": 0, "key1": 1}],
"key5": [],
"key6": [[]],
"key7": [["text"]],
"key8": [[{"key0": 0}]]
}

new_data = {k: delist(v) for k, v in data.items()}

new_data

{'key1': 'text',
'key2': ['text', 'text'],
'key3': {'key0': 0},
'key4': {'key0': 0, 'key1': 1},
'key5': '',
'key6': '',
'key7': 'text',
'key8': {'key0': 0}}

关于python - 将包含一项的列表转换为字典值中的项本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71682367/

25 4 0
文章推荐: rust - 如何在 Rust 中写入最大缓冲区大小的格式化字符串?
文章推荐: css - NextJS 中的 组件似乎丢失了带有
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com