我正在尝试在dicts列表中打印特定键的值:
例如:
list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
我希望能够为每个字典打印以下内容:
print ("a: ", a)
print ("b: ", b)
答案 0 :(得分:1)
如果您确信这些密钥存在,那么使用operator.itemgetter
:
from operator import itemgetter
# Renamed your list; don't name variables list
for a, b in map(itemgetter('a', 'b'), mylist):
print("a:", a)
print("b:", b)
以上只是导入免费代码的略微优化版本,推动了将值提取到内置函数的工作,而不是一遍又一遍地执行。
for d in mylist: # Renamed your list; don't name variables list
print("a:", d['a'])
print("b:", d['b'])
哦,为了完整性(Aaron Hall说得很好,避免冗余代码),调整itemgetter
用法来观察DRY规则:
keys = ('a', 'b')
for values in map(itemgetter(*keys), mylist):
for k, v in zip(keys, values):
print(k, v, sep=": ")
答案 1 :(得分:0)
一些嵌套循环怎么样,以避免硬编码?
for dictionary in list: # rename list so you don't overshadow the builtin list
for key in ('a', 'b'):
print(key + ':', dictionary[key])
应输出:
a: 123
b: xyz
a: 456
b: cde
答案 2 :(得分:0)
lst = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
output=['a','b']
for dct in lst:
for k in output:
print(k+': '+str(dct[k]))