英文:
Better way to index through list of dictionaries
问题
我有这段糟糕的代码,我试图解析一个包含字典列表的字典列表。
如果 id 匹配特定的 id,我需要输出一个包含 id 和 name 的字典列表,类似于这样:
```python
[{"id": 123}, {'name': 'bob'}]
list1 = [{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]}, {"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
list2 = []
keys = ["id", "who"]
for items in list1:
if items['id'] == 123:
for key in keys:
if key == "who":
for values in items[key]:
for count in values:
if count == "name":
list2.append({key : values[count]})
else:
list2.append({key : items[key]})
print(list2)
目前代码可以工作,但看起来像猴子写的!我该如何让它更有效率?
<details>
<summary>英文:</summary>
I have this awful awful code where I am trying to parse through a list of dictionaries which contain a list of dictionaries.
I need to output a list of dictionaries with the id and name like this if the id matches a certain id. Something like this:
[{"id": 123}, {'name': 'bob'}]
list1 = [{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]}, {"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
list2 = []
keys = ["id", "who"]
for items in list1:
if items['id'] == 123:
for key in keys:
if key == "who":
for values in items[key]:
for count in values:
if count == "name":
list2.append({key : values[count]})
else:
list2.append({key : items[key]})
print(list2)
Code currently works but looks like a monkey wrote it! How can I make this more efficient?
</details>
# 答案1
**得分**: 1
How about simply accessing the element of lists and dictionaries together with slicing?
```python
list1 = [
{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
{"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
{"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
]
# Input
target_keys = ["id", "who"]
target_ids = [123, 234]
# Output
result_list = []
for item in list1:
if item['id'] in target_ids:
result_list.append([
{"id": item[target_keys[0]]},
{"name": item[target_keys[1]][0]['name']}
])
print(result_list)
英文:
How about simply accessing the element of lists and dictionaries together with slicing?
list1 = [
{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
{"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
{"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
]
# Input
target_keys = ["id", "who"]
target_ids = [123, 234]
# Output
result_list = []
for item in list1:
if item['id'] in target_ids:
result_list.append([
{"id": item[target_keys[0]]}, # {"id": item['id']},
{"name": item[target_keys[1]][0]['name']}, # {"name": item['who'][0]['name']}
])
print(result_list)
答案2
得分: 1
使用Python版本:3.8或更高
list1 = [{"id": 123, "job": "nurse", "who": [{"user": "bob_user", "name": "bob"}]},
{"id": 456, "job": "teacher", "who": [{"user": "jim_user", "name": "jim"}]}]
list2 = []
keys = ["id", "who"]
find_ids = [123, 456]
for data in list1:
# 在检查“id”是否匹配“find_ids”列表中的id时
# 将“id”值赋给变量“user_id”
if (user_id := data.get("id")) in find_ids:
user_name = data.get("who")[0].get("name")
list2.append({"id": user_id, "who": user_name})
print(list2)
# 输出:
# [{'id': 123, 'who': 'bob'}, {'id': 456, 'who': 'jim'}]
英文:
use Python version: 3.8 or above
list1 = [{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
{"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}]
list2 = []
keys = ["id", "who"]
find_ids = [123, 456]
for data in list1:
# while checking if the "id" matches list of ids in "find_ids"
# We are assigning the "id" value to variable "user_id"
if (user_id:=data.get("id")) in find_ids:
user_name = data.get("who")[0].get("name")
list2.append({"id": user_id, "who": user_name})
print(list2)
# output:
# [{'id': 123, 'who': 'bob'}, {'id': 456, 'who': 'jim'}]
答案3
得分: 1
你可以使用Pythonic列表推导式将这段代码简化为一行。根据@Jiho Choi的示例,假设输入是多个目标ID,并且假设"who"键的数组值只包含一个字典项,这将是最简洁的解决方案:
list1 = [
{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
{"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
{"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
]
# 输入
target_ids = [123, 234]
# 输出
result_list = [{"id": x["id"], "who": x["who"][0]["name"]} for x in list1 if x["id"] in target_ids]
print(result_list)
英文:
You can simplify this code into a one-liner using Pythonic list comprehension.
Branching off of @Jiho Choi's example of an input of multiple target_ids and assuming the array value of the key "who" only has a single dictionary item, this would be your most concise solution:
list1 = [
{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
{"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
{"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
]
# Input
target_ids = [123, 234]
# Output
result_list = [[{'id': x['id']}, {'who': x['who'][0]['name']}] for x in list1 if x['id'] in target_ids]
print(result_list)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论