test_data = [
{"name": "路飞", "age": 18, "from": "Donghai sea"},
{"name": "索隆", "age": 18, "from": "Xihai sea"}
for hz in test_data: # 遍历 test_data 数组中的每个字典
name = hz.get('name') # 每个字典使用get()方法获取"name"和"age"键对应的值
birthplace = hz.get('from') # 并将他们存在 name和birthplace变量中
if name and birthplace: # 使用if条件语句检查是否成功获取了这两个值
print(name) # 满足条件打印
print(birthplace)
使用循环遍历数组中的每个字典,然后使用键值对来访问对应的值。
适用于数组中包含多个字典且每个字典的结构不同。
test_data = [
{"name": "路飞", "age": 18, "from": "Donghai sea"},
{"name": "索隆", "age": 18, "from": "Xihai sea"}
keys = ['name', 'from']
result = []
for hz in test_data:
values = {key: hz.get(key) for key in keys}
result.append(values)
print(result)
使用列表推导式。
适用于数组中包含多个字典且每个字典的结构相同。
test_data = [
{"name": "路飞", "age": 18, "from": "Donghai sea"},
{"name": "索隆", "age": 18, "from": "Xihai sea"}
keys = ['name', 'age', 'from']
result = [[hz[key] for key in keys] for hz in test_data]
print(result)
使用列表推导式和zip()函数。遍历数组中的每个字典,使用values()方式获取每个字典的所有值,并使用zip()函数将指定的键(keys)与对应的值进行配对。
然后,通过使用dict()函数将配对的键值转换为新的字典。
好处是,这种方法它创建一个新的字典,其中只包含指定的键值对,而不需要在原始的字典中进行修改。
test_data = [
{"name": "路飞", "age": 18, "from": "Donghai sea"},
{"name": "索隆", "age": 18, "from": "Xihai sea"}
keys = ['name', 'from']
result = [dict(zip(keys, item.values())) for item in test_data]
print(result)
如果只需要从一个字典中获取特定的键值对,而不是从数组中的多个字典中获取,可使用如下方法。
test_data = {
"name": "路飞",
"age": 18,
"from": "Donghai sea"
keys = ['name', 'age', 'from']
values = [test_data[key] for key in keys]
print(values)