英文:
get certain keys from the dictionary and spread remaining into another dictionary
问题
{
"I have a dictionary that looks like this": "我有一个类似这样的字典",
"{": "{",
""name": "id"," : "“name”: “id”",
""data_type": "int"," : "“data_type”: “int”",
""min_value": "10"," : "“min_value”: “10”",
""max_value": "110"" : "“max_value”: “110”",
"}": "}",
"I want to convert it into a tuple where the first two parameters are values of the first two keys, while the rest is the dictionary": "我想将其转换为一个元组,其中前两个参数是前两个键的值,而其余部分是字典",
"(id, int, {min_value: 10, max_value: 110})": "(id, int, {min_value: 10, max_value: 110})",
"When I do like this": "当我这样做时",
"for item in input:": "对于输入中的项目:",
"name = item['name']": "name = item['name']",
"del item['name']": "del item['name']",
"data_type = item['data_type']": "data_type = item['data_type']",
"del item['data_type']": "del item['data_type']",
"tup = (name, data_type, {**item})": "tup = (name, data_type, {**item})",
"print(tup) # ('id', 'int', {'min_value': 10, 'max_value': 110})": "print(tup) # ('id', 'int', {'min_value': 10, 'max_value': 110})",
"It works fine, but I wonder if there is a better way to do that?": "这样做可以正常工作,但我想知道是否有更好的方法?"
}
英文:
I have a dictionary that looks like this
{
"name": "id",
"data_type": "int",
"min_value": "10",
"max_value": "110"
}
I want to convert it into a tuple where the first two parameters are values of the first two keys, while the rest is the dictionary
(id, int, {min_value: 10, max_value: 110})
When I do like this
for item in input:
name = item['name']
del item['name']
data_type = item['data_type']
del item['data_type']
tup = (name, data_type, {**item})
print(tup) # ('id', 'int', {'min_value': 10, 'max_value': 110})
It works fine, but I wonder if there is a better way to do that?
答案1
得分: 1
这应该可以:
tup = item.pop('name'), item.pop('data_type'), item
评估顺序被保证为从左到右,因此这应该是一个安全的操作。请注意,它修改了item
;如果你不希望这样,你应该先复制一份。
英文:
This should do:
tup = item.pop('name'), item.pop('data_type'), item
The evaluation order is guaranteed to be left to right, so this should be a safe operation. Note that it modifies item
; if you don't want that, you'll want to make a copy of it first.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论