打印字典中的值而不包含空列表

时间:2018-08-27 04:48:18

标签: python list dictionary

我有以下数据:

d = d = [ {
  "test" : [ {
    "win" : {
      "number" : 0
    },
    "taken" : [ {
      "id" : "0",
      "library" : [ ]
    } ]
  }, {
    "win" : {
      "number" : 1
    },
    "taken" : [ {
      "id" : "1",
      "library" : [ {
        "takenid" : "2",
        "lib" : "man"
      } ]
    }, {
      "id" : "2",
    } ]
  }, {
    "chunk" : {
      "number" : 2
    },
    "taken" : [ {
      "id" : "3",
      "library" : [ {
        "takenid" : "0",
        "lib" : "woman"
      }, {
        "takenid" : "1",
        "lib" : "ghost"
      }, {
        "takenid" : "4",
        "lib" : "monster"
      } ]
    }, {
      "id" : "4"
    } ]
  } ]
} ]

我想打印“ lib”字典的所有值,而不是空列表。在我的代码中,我将检查总的“ id”并将其与“ takenid”进行比较,然后根据缺失值添加新的“ takenid”。之后,我希望创建一个字典,其形式为{id:{takenid:lib}},但不包括空列表(新添加的“ takenid”和“ lib”)。

下面是我的脚本代码:

acom = []
lemmas = []
ordering = []
sort = []      

check = 0
for x in d[0]["test"]:
    for y in x["taken"]:
        if "id" in y:
            check += 1

value = []
#Calculate the number of "takenid"
for x in d[0]["test"]:
    for y in x["taken"]:
        if "library" in y:
            for u in y["library"]:
                value.append(int(u["takenid"]))
#Find the difference between the "id" and "takenid"                
missing = (set(range(check)) - set(value))
missing = list(missing)
#print(missing)

for x in d[0]["test"]:
    for y in x["taken"]:
        if "library" in y:
            y["library"].append({"takenid": "%s" % missing[0], "lib": []})
    break                    
#Create a dictionary                             
for x in d[0]["test"]:
    for y in x["taken"]:
        if "library" in y:
            for u in y["library"]:
                if "[]" not in u["lib"]:
                    #if "[]" not in uu:
                       ordering.append({y["id"]:{u["takenid"]:u["lib"]}})



#print(ordering)

但是,我的代码接受了一个空列表并打印了此输出:

当前输出:

[{'0': {'3': []}}, {'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'4': 'monster'}}]

我希望创建一个没有空列表的字典。有可能这样做吗?

预期输出:

[ {'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'4': 'monster'}}]

2 个答案:

答案 0 :(得分:2)

可能是"[]"引起的问题。将"[]"更改为[]

if "[]" not in u["lib"]:更改为if u["lib"]:即可完成工作。

说明:

"[]" not in u["lib"]的意思是'find substring "[]" in u["lib"]'。但在您的u["lib"]中仅包含字符串或空列表。因此只要评估价值存在,就会为您提供正确的答案。

答案 1 :(得分:1)

更短的选择:

[{baz['id']: {quux['takenid']: quux['lib']}}
    for foo in d
    for k, v in foo.items()
    for bar in v
    for kk, vv in bar.items()
    for baz in vv if 'library' in baz and baz['library']
    for quux in baz['library']
]
# => [{'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'4': 'monster'}}]

在这里,if 'library' in baz and baz['library']将检查library键是否存在并且不为空。