所以我有以下字典列表
myList = [{'one':1, 'two':2,'three':3},
{'one':4, 'two':5,'three':6},
{'one':7, 'two':8,'three':9}]
这只是我所拥有字典的一个示例。我的问题是,有可能以某种方式将所有字典中的说two
修改为它们的值的两倍,这是使用列表理解吗?
我知道如何使用列表理解来创建字典的新列表,但是不知道如何修改它们,我想出了类似的方法
new_list = { <some if condiftion> for (k,v) in x.iteritems() for x in myList }
我不确定如何在<some if condiftion>
中指定条件,我认为嵌套列表理解格式也是正确的吗?
我想要像这样的示例的最终输出
[ {'one':1, 'two':4,'three':3},{'one':4, 'two':10,'three':6},{'one':7, 'two':16,'three':9} ]
答案 0 :(得分:4)
使用列表推导和嵌套dict推导:
$ gcc-4.6 -o test.modified main.c delay.modified.o
$ gdb ./test.modified
.
.
.
(gdb) break *delay+0x18
Breakpoint 1 at 0x103cc: file delay.c, line 4.
(gdb) run
Starting program: /home/pi/test.modified
Breakpoint 1, 0x000103cc in delay (num=3) at delay.c:4
4 for(i=0; i<num; i++);
(gdb) print i
$1 = 0
(gdb) cont
Continuing.
Breakpoint 1, 0x000103cc in delay (num=3) at delay.c:4
4 for(i=0; i<num; i++);
(gdb) print i
$2 = 1
(gdb) cont
Continuing.
Breakpoint 1, 0x000103cc in delay (num=3) at delay.c:4
4 for(i=0; i<num; i++);
(gdb) print i
$3 = 2
(gdb) cont
Continuing.
[Inferior 1 (process 30954) exited with code 03]
(gdb)
答案 1 :(得分:1)
myList = [ {'one':1, 'two':2,'three':3},{'one':4, 'two':5,'three':6},{'one':7, 'two':8,'three':9} ]
[ { k: 2*i[k] if k == 'two' else i[k] for k in i } for i in myList ]
[{'one': 1, 'three': 3, 'two': 4}, {'one': 4, 'three': 6, 'two': 10}, {'one': 7, 'three': 9, 'two': 16}]
答案 2 :(得分:1)
一个简单的for
循环就足够了。但是,如果要使用字典理解,我发现定义映射字典比三元语句更易读和可扩展:
factor = {'two': 2}
res = [{k: v*factor.get(k, 1) for k, v in d.items()} for d in myList]
print(res)
[{'one': 1, 'two': 4, 'three': 3},
{'one': 4, 'two': 10, 'three': 6},
{'one': 7, 'two': 16, 'three': 9}]
答案 3 :(得分:0)
您好吗?
for d in myList:
d.update((k, v*2) for k, v in d.iteritems() if k == "two")
谢谢
答案 4 :(得分:0)
在python 3.5+中,您可以在PEP 448中引入的dict文字中使用新的解包语法。这将创建每个字典的副本,然后覆盖键two
的值:
new_list = [{**d, 'two': d['two']*2} for d in myList]
# result:
# [{'one': 1, 'two': 4, 'three': 3},
# {'one': 4, 'two': 10, 'three': 6},
# {'one': 7, 'two': 16, 'three': 9}]