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

时间:2020-08-05 10:29:56

标签: python dictionary

我在下面有一本字典

  • 我首先要检查包含MainContract的父母。
  • 主要将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"
          },
        ]}

预期在下面

 {"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"
      },
    ]}

代码

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']

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

2 个答案:

答案 0 :(得分:0)

您的for循环被误导了。

您犯了3个错误:

  1. 您尝试遍历父字典而不是实际雇员列表。
  2. 您正在倒退使用x in y,以检查一个字符串是否包含另一个。
  3. 您实际上并没有将新名称添加到“级别”列表中。

尝试一下:

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"]]

这将为您提供“级别”,作为员工的dict“兄弟姐妹”(而不是您真正想要的员工列表)。

要获得所需的 exact 结果,您必须执行以下操作:

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"]

答案 1 :(得分:0)

尝试一下:

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)

输出:

{'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'}]}