[英]How to get dictionary with just the key and GIDs from a larger dictionary?
This returns a list of all the gids.这将返回所有 gid 的列表。 I would like it so that all gids are reachable by their key.我希望所有 gids 都可以通过他们的密钥访问。 eg例如{0: "23172371321","123421412343",1" "12312412214","123124124"}
. {0: "23172371321","123421412343",1" "12312412214","123124124"}
。
The GID are accessible by the code task_gid_dict[j][i]["gid"]
GID 可通过代码task_gid_dict[j][i]["gid"]
访问
i = 0
j = 0
task_gid_dict_2 = {}
for i in range(len(task_gid_dict)):
while True:
try:
task_gid.append(task_gid_dict[j][i]["gid"])
i = i+1
except:
j = j+1
break
task_gid_dict_2[j] = task_gid
task_gid_dict_2
At then moment it looks like this task_gid_dict = {0: [{'gid': '1199729685867432', 'name': 'SAMPLE', 'resource_type': 'task', 'resource_subtype': 'default_task'},
...那时它看起来像这个 task_gid_dict = {0: [{'gid': '1199729685867432', 'name': 'SAMPLE', 'resource_type': 'task', 'resource_subtype': 'default_task'},
...
EXTRA:额外的:
task_detail = {}
for k,i in task_gid_dict.items():
task_detail[i] = client.tasks.get_task(task_gid_2[k][i], {'param': 'value', 'param': 'value'}, opt_pretty=True)
task_detail
Your output will look a little different from what you have up top.您的 output 看起来与您在上面的有所不同。 A dict stores a single value for a single key, but the value can be a list object, so instead of 0: 123456789, 987654321, you'll have 0: [123456789, 987654321].字典存储单个键的单个值,但该值可以是列表 object,因此您将得到 0:[123456789、987654321] 而不是 0:123456789、987654321。
task_gid_dict_2 = {}
# iterate through key value pairs of a dictionary
for k, v in task_gid_dict.items():
# initialize the key in the new dict with an empty list
task_gid_dict_2[k] = []
# iterate through the sub-dictionaries in each value
for sub_dict in v:
# Add the gid from the sub-dict to your new list
task_gid_dict_2.append(sub_dict['gid'])
That gets you what you want and I think makes the most sense, but if you want to take it a step further, you could do it with a combined dict and list comprehension as well:这会让你得到你想要的,我认为这是最有意义的,但如果你想更进一步,你也可以通过组合的 dict 和列表理解来做到这一点:
task_gid_2 = {k: [sub_d['gid'] for sub_d in v] for k, v in task_gid_dict.items()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.