从Python中的Dictionary打印特定键的值

问题描述 投票:0回答:2

我有Input.txt,此文件的内容是:

Name1=Value1
Name2=Value2
Name3=Value3

所需的输出:获取key==Name1的值。

条件:这需要由Python中的Dictionary实现。

python python-3.x dictionary key-value
2个回答
1
投票
with open("Input.txt", "r") as param_file:
    text = param_file.readlines()
    d = dict(x.strip().split("=") for x in text)
    for k, v in d.items():
        if k == "Name1":
            print(f"{d[k]}")

0
投票

您可以做

with open("Input.txt", "r") as param_file:
    text = param_file.readlines()
    dc = {y.split("=")[0]:y.split("=")[1] for y in [i for i in a.split(" ")]}
    print(dc["Name1"]) if "Name1" in dc else None

将输出

Value1
© www.soinside.com 2019 - 2024. All rights reserved.