简体   繁体   English

如果值包含特定字符串,如何创建字典

[英]How to create a dictionary if value contain a particular string

I have a dictionary below我在下面有一本字典

  • Fist i need to check a parent which contain Main or Contract .拳头我需要检查包含MainContract的父级。
  • FOr Main add name to the level1 dictionary and Contract level2 dictionary FOR Main 将name添加到 level1 字典和 Contract level2 字典
    d = {"employee": [
          {
            "id": "18",
            "name": "Manager",
            "parent": "Main level"
          },
          {
            "id": "19",
            "name": "Employee",
            "parent": "Main level"
          },
          {
            "id": "32",
            "name": "Contract",
            "parent": "Contract level"
          },
              {
            "id": "21",
            "name": "Admin",
            "parent": "Main level"
          },
        ]}

Expected out is below预期结果如下

 {"employee": [
    {'level1':['Manager','Employee']},
    {'level2':['Test','HR']},
      {
        "id": "18",
        "name": "Manager",
        "parent": "Main level"
      },
      {
        "id": "19",
        "name": "Employee",
        "parent": "Main level"
      },
      {
        "id": "32",
        "name": "Test",
        "parent": "Contract level"
      },
          {
        "id": "21",
        "name": "HR",
        "parent": "Contract level"
      },
    ]}

Code代码

d['level1'] = {}
d['level2'] = {}
for i,j in d.items():
  #check parent is Main 
  if j['parent'] in 'Main':
      d['level1'] = j['name']
  if j['parent'] in 'Contract':
      d['level2'] = j['name']

I got the error TypeError: list indices must be integers or slices, not str我收到错误TypeError: list indices must be integers or slices, not str

Your for loop is misguided.for循环被误导了。

You made 3 mistakes:你犯了3个错误:

  1. You tried looping over the parent dict instead of the actual list of employees.您尝试循环遍历父 dict 而不是实际的员工列表。
  2. You are using x in y backwards, for checking if one string contains another.您正在向后使用x in y来检查一个字符串是否包含另一个字符串。
  3. You are not actually appending new names to the "levels" lists.您实际上并没有将新名称附加到“级别”列表中。

Try this:尝试这个:

d["level1"] = []
d["level2"] = []
for j in d["employee"]:
    # check parent is Main
    if "Main" in j["parent"]:
        d["level1"] += [j["name"]]
    if "Contract" in j["parent"]:
        d["level2"] += [j["name"]]

That will give you the "levels" as dict "siblings" of the employees (instead of in the list of employees, which is what you actually want).这将为您提供“级别”作为员工的“兄弟姐妹”(而不是在员工列表中,这是您真正想要的)。

To get the exact result you want, you would have to do something like this:要获得您想要的确切结果,您必须执行以下操作:

level1 = []
level2 = []
for j in d["employee"]:
    # check parent is Main
    if "Main" in j["parent"]:
        level1 += [j["name"]]
    if "Contract" in j["parent"]:
        level2 += [j["name"]]

d["employee"] = [{"level1": level1}, {"level2": level2}] + d["employee"]

Try this:尝试这个:

dd = {'Main level': 'level1', 'Contract level': 'level2'}

res = {}
for x in d['employee']:
    k = dd[x['parent']]
    if k in res:
        res[k].append(x['name'])
    else:
        res[k] = [x['name']]

d['employee'] = [{k: v} for k, v in res.items()] + d['employee']
print(d)

Output: Output:

{'employee': [{'level1': ['Manager', 'Employee', 'Admin']},
  {'level2': ['Contract']},
  {'id': '18', 'name': 'Manager', 'parent': 'Main level'},
  {'id': '19', 'name': 'Employee', 'parent': 'Main level'},
  {'id': '32', 'name': 'Contract', 'parent': 'Contract level'},
  {'id': '21', 'name': 'Admin', 'parent': 'Main level'}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM