根据value, 获取列表字典数据中对应元素,代码如下:
def getIndex(li, val, whichKey=None):
l = []
for num, i in enumerate(li):
l += ((num, i.get(whichKey), k) for k, v in i.items() if v == val)
return l
详解:
def getIndex(li, val, whichKey=None):
"""
:param li: 数据data
:param val: 查询的value值
:param whichKey: 显示字典数据的关键字key, 不传则为None
:return: 查询到的 包含 value 的, 元素的元组列表,[(index, whichKey, key),...]
"""
l = []
# 获取列表<数据i>及其<下标num>
for num, i in enumerate(li):
# i 为 字典, 形如{key1: value1, key2: value2}
# 追加数据 查询的val对应的 num, whichKey, key 到列表 l 中
l += ((num, i.get(whichKey), k) for k, v in i.items() if v == val)
return l
d = [{"name": 'Tony', 'a': 12, 'c': 12}, {"name": 'Peter', 'g': 12}, {"name": 'Tom', 'k': 33}, {"name": 'Tom', 'l': 12}]
res = getIndex(d, 12)
print(res)
[(0, None, 'a'), (0, None, 'c'), (1, None, 'g'), (3, None, 'l')]
res2 = getIndex(d, 12, 'name')
print(res2)
[(0, 'Tony', 'a'), (0, 'Tony', 'c'), (1, 'Peter', 'g'), (3, 'Tom', 'l')]
网友评论