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

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

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 = [
    {&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;}]},
    {&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;}]},
    {&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;}]}
]

# Input
target_keys = [&quot;id&quot;, &quot;who&quot;]
target_ids = [123, 234]

# Output
result_list = []
for item in list1:
    if item[&#39;id&#39;] in target_ids:
        result_list.append([
            {&quot;id&quot;: item[target_keys[0]]},               # {&quot;id&quot;: item[&#39;id&#39;]},
            {&quot;name&quot;: item[target_keys[1]][0][&#39;name&#39;]},  # {&quot;name&quot;: item[&#39;who&#39;][0][&#39;name&#39;]}
        ])
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 = [{&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;}]}, 
         {&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;}]}]
list2 = []
keys = [&quot;id&quot;, &quot;who&quot;]
find_ids = [123, 456]

for data in list1:
    # while checking if the &quot;id&quot; matches list of ids in &quot;find_ids&quot;
    # We are assigning the &quot;id&quot; value to variable &quot;user_id&quot;
    if (user_id:=data.get(&quot;id&quot;)) in find_ids:
        user_name = data.get(&quot;who&quot;)[0].get(&quot;name&quot;)
        list2.append({&quot;id&quot;: user_id, &quot;who&quot;: user_name})
print(list2)
# output:
# [{&#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"键的数组值只包含一个字典项,这将是最简洁的解决方案:

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 = [
        {&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;}]},
        {&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;}]},
        {&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;}]}
        ]
# Input
target_ids = [123, 234]

# Output
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]
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:

确定