Python:如何过滤字典?

标签 python pandas dictionary

我想实现以下目标,但要使用字典。

name_selected = "Jason"

if name_selected == "John":
    age = 10
    gender = "Male"
elif name_selected == "Jason":
    age = 20
    gender = "Male"

print(age, gender)
data = {"name": ["John", "Jason"],
         "age": [10, 20],
      "gender": ["Male", "Male"]}

最佳答案

这是一个糟糕的数据组织。如果将名称作为字典键会更好:

data = {
    "John": { "age": 10, "gender": "Male"},
    "Jason": { "age": 20, "gender": "Male"}
}

age = data[name_selected]["age"]
gender = data[name_selected]["gender"]

但是如果你被你的数据结构困住了,你可以使用 index() 来获取 name 元素中的索引,然后使用它来获取相应的其他元素中的值。

try:
    index = data['name'].index(name_selected)
    age = data['age'][index]
    gender = data['gender'][index]
except:
    print(f'{name_selected} not found')

关于Python:如何过滤字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67507210/

相关文章:

python - "import __hello__"是如何工作的?

Python:在 Pandas 数据帧上使用多处理

python - 在方法链中用 nan 替换数据帧列负值

python - Pandas 成群移动缓慢

swift - 错误 : Immutable value passed on reduce function

dictionary - 如何在 Dart 中通过值获取 Map 键?

python - 在Python中更改.bmp文件的图像分辨率

python - pandas 在pivot_table期间聚合多个列

python将所有键转换为字符串

python - 导入 StanfordNER Tagger Google Colab