从字典中获取特定键,并将其余部分展开到另一个字典。

huangapple go评论54阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月8日 17:44:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定