更好的方式来遍历字典列表

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

Better way to index through list of dictionaries

问题

  1. 我有这段糟糕的代码我试图解析一个包含字典列表的字典列表
  2. 如果 id 匹配特定的 id我需要输出一个包含 id name 的字典列表类似于这样
  3. ```python
  4. [{"id": 123}, {'name': 'bob'}]
  1. list1 = [{"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]}, {"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
  2. list2 = []
  3. keys = ["id", "who"]
  4. for items in list1:
  5. if items['id'] == 123:
  6. for key in keys:
  7. if key == "who":
  8. for values in items[key]:
  9. for count in values:
  10. if count == "name":
  11. list2.append({key : values[count]})
  12. else:
  13. list2.append({key : items[key]})
  14. print(list2)

目前代码可以工作,但看起来像猴子写的!我该如何让它更有效率?

  1. <details>
  2. <summary>英文:</summary>
  3. I have this awful awful code where I am trying to parse through a list of dictionaries which contain a list of dictionaries.
  4. 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)

  1. Code currently works but looks like a monkey wrote it! How can I make this more efficient?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. How about simply accessing the element of lists and dictionaries together with slicing?
  6. ```python
  7. list1 = [
  8. {"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
  9. {"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
  10. {"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
  11. ]
  12. # Input
  13. target_keys = ["id", "who"]
  14. target_ids = [123, 234]
  15. # Output
  16. result_list = []
  17. for item in list1:
  18. if item['id'] in target_ids:
  19. result_list.append([
  20. {"id": item[target_keys[0]]},
  21. {"name": item[target_keys[1]][0]['name']}
  22. ])
  23. print(result_list)
英文:

How about simply accessing the element of lists and dictionaries together with slicing?

  1. list1 = [
  2. {&quot;id&quot;: 123, &quot;job&quot;: &quot;nurse&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;bob_user&quot;, &quot;name&quot;: &quot;bob&quot;}]},
  3. {&quot;id&quot;: 234, &quot;job&quot;: &quot;programmer&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;alice_user&quot;, &quot;name&quot;: &quot;alice&quot;}]},
  4. {&quot;id&quot;: 456, &quot;job&quot;: &quot;teacher&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;jim_user&quot;, &quot;name&quot;: &quot;jim&quot;}]}
  5. ]
  6. # Input
  7. target_keys = [&quot;id&quot;, &quot;who&quot;]
  8. target_ids = [123, 234]
  9. # Output
  10. result_list = []
  11. for item in list1:
  12. if item[&#39;id&#39;] in target_ids:
  13. result_list.append([
  14. {&quot;id&quot;: item[target_keys[0]]}, # {&quot;id&quot;: item[&#39;id&#39;]},
  15. {&quot;name&quot;: item[target_keys[1]][0][&#39;name&#39;]}, # {&quot;name&quot;: item[&#39;who&#39;][0][&#39;name&#39;]}
  16. ])
  17. print(result_list)

答案2

得分: 1

使用Python版本:3.8或更高

  1. list1 = [{"id": 123, "job": "nurse", "who": [{"user": "bob_user", "name": "bob"}]},
  2. {"id": 456, "job": "teacher", "who": [{"user": "jim_user", "name": "jim"}]}]
  3. list2 = []
  4. keys = ["id", "who"]
  5. find_ids = [123, 456]
  6. for data in list1:
  7. # 在检查“id”是否匹配“find_ids”列表中的id时
  8. # 将“id”值赋给变量“user_id”
  9. if (user_id := data.get("id")) in find_ids:
  10. user_name = data.get("who")[0].get("name")
  11. list2.append({"id": user_id, "who": user_name})
  12. print(list2)
  13. # 输出:
  14. # [{'id': 123, 'who': 'bob'}, {'id': 456, 'who': 'jim'}]
英文:

use Python version: 3.8 or above

  1. list1 = [{&quot;id&quot;: 123, &quot;job&quot;: &quot;nurse&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;bob_user&quot;, &quot;name&quot;: &quot;bob&quot;}]},
  2. {&quot;id&quot;: 456, &quot;job&quot;: &quot;teacher&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;jim_user&quot;, &quot;name&quot;: &quot;jim&quot;}]}]
  3. list2 = []
  4. keys = [&quot;id&quot;, &quot;who&quot;]
  5. find_ids = [123, 456]
  6. for data in list1:
  7. # while checking if the &quot;id&quot; matches list of ids in &quot;find_ids&quot;
  8. # We are assigning the &quot;id&quot; value to variable &quot;user_id&quot;
  9. if (user_id:=data.get(&quot;id&quot;)) in find_ids:
  10. user_name = data.get(&quot;who&quot;)[0].get(&quot;name&quot;)
  11. list2.append({&quot;id&quot;: user_id, &quot;who&quot;: user_name})
  12. print(list2)
  13. # output:
  14. # [{&#39;id&#39;: 123, &#39;who&#39;: &#39;bob&#39;}, {&#39;id&#39;: 456, &#39;who&#39;: &#39;jim&#39;}]

答案3

得分: 1

你可以使用Pythonic列表推导式将这段代码简化为一行。根据@Jiho Choi的示例,假设输入是多个目标ID,并且假设"who"键的数组值只包含一个字典项,这将是最简洁的解决方案:

  1. list1 = [
  2. {"id": 123, "job": "nurse", "who":[{"user": "bob_user", "name": "bob"}]},
  3. {"id": 234, "job": "programmer", "who":[{"user": "alice_user", "name": "alice"}]},
  4. {"id": 456, "job": "teacher", "who":[{"user": "jim_user", "name": "jim"}]}
  5. ]
  6. # 输入
  7. target_ids = [123, 234]
  8. # 输出
  9. result_list = [{"id": x["id"], "who": x["who"][0]["name"]} for x in list1 if x["id"] in target_ids]
  10. 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:

  1. list1 = [
  2. {&quot;id&quot;: 123, &quot;job&quot;: &quot;nurse&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;bob_user&quot;, &quot;name&quot;: &quot;bob&quot;}]},
  3. {&quot;id&quot;: 234, &quot;job&quot;: &quot;programmer&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;alice_user&quot;, &quot;name&quot;: &quot;alice&quot;}]},
  4. {&quot;id&quot;: 456, &quot;job&quot;: &quot;teacher&quot;, &quot;who&quot;:[{&quot;user&quot;: &quot;jim_user&quot;, &quot;name&quot;: &quot;jim&quot;}]}
  5. ]
  6. # Input
  7. target_ids = [123, 234]
  8. # Output
  9. result_list = [[{&#39;id&#39;: x[&#39;id&#39;]}, {&#39;who&#39;: x[&#39;who&#39;][0][&#39;name&#39;]}] for x in list1 if x[&#39;id&#39;] in target_ids]
  10. print(result_list)

huangapple
  • 本文由 发表于 2023年5月18日 09:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277200.html
匿名

发表评论

匿名网友

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

确定