2012-12-22 51 views
0

我正在让自己陷入嵌套的困境。操纵嵌套在词典中的标签列表(.lstrip())嵌套在字典列表中

我有一个看起来像这样的Python对象的列表:

notes = [ 
    {'id':1, 
     'title':'title1', 
     'text':'bla1 bla1 bla1', 
     'tags':['tag1a', ' tag1b', ' tag1c']}, 
    {'id':2, 
     'title':'title2', 
     'text':'bla2 bla2 bla2', 
     'tags':[' tag2a', ' tag2b', ' tag2c']}, 
    {'id':3, 
     'title':'title3', 
     'text':'bla3 bla3 bla3', 
     'tags':[' tag3a', ' tag3b', ' tag3c']}] 

等。

我想进入列表中的每个字典,并去掉左空格,并返回字典列表,其中唯一的区别是标签有其不必要的空白空白。

下面的代码是我正在使用的,但它是不正确的,我不知道我在做什么来得到我需要的结果。

notes_cleaned = [] 
for objs in notes: 
    for items in objs: 
     notes_cleaned.append({'text':n['text'], 'id':n['id'], 'tags':[z.lstrip(' ') for z in n['tags']], 'title':n['title']}) 

这给了我,我不能使用字符串下标,这是我理解错误,但我不知道怎么做是正确的。因为我知道,我必须每个字典遍历,如:

for objs in notes: 
    for items in objs: 
     print items, objs[items] 

,但我很困惑,如何去重建词典,同时挖掘到标签列表专门的最后一部分。

我在这里错过了什么(知道我肯定错过了什么)。

回答

1

下面的代码应该假设只有“标签”需要被剥离:

def clean(items): 
    clean = [] 
    for objs in items: 
     nObj = {} 
     for item, obj in objs.iteritems(): 
      if item != "tags": 
       nObj[item] = obj 
      else: 
       nObj["tags"] = [n.lstrip() for n in obj] 
     clean.append(nObj) 
    return clean 
+0

谢谢,这是最明确的解释,所以我选择了这一个。 – roy

2

我觉得这就够了:

for note in notes: 
    note['tags']= [t.strip() for t in note['tags']] 

如果你真的需要在复制操作(笔记),你可以很容易地得到它:copy= map(dict, notes)

+0

请注意'map(dict,notes)'只会制作'notes'的浅拷贝 - 他们会共享'tags'列表。 – DSM

+0

@DSM是的,如果你想对列表做一些其他的事情,那么值得一提的是,如果你在'for'之后这样做,它不适用,因为列表被重新创建。 – goncalopp

+0

还没有考虑过map(),但很酷。此外,非常直接的代码谢谢! – roy

2
python 3.2 

    # if you want the dict which value is list and string within the list stripped 

    [{i:[j.strip() for j in v] for i,v in k.items()if isinstance(v,list)} for k in notes] 



    # if you want the dict which value is list and those string within the list 
    stripped which has whitespace 

    [{i:[j.strip() for j in v if " " in j] for i,v in k.items()if isinstance(v,list)} 
        for k in n] 
+0

假设我应该添加我仍然在python 2.7上,但这仍然有帮助。谢谢! – roy