【问题标题】:Print the value of specific key from Dictionary in Python从 Python 中的 Dictionary 打印特定键的值
【发布时间】:2020-05-12 10:27:01
【问题描述】:

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

Name1=Value1
Name2=Value2
Name3=Value3

想要的输出:获取key==Name1的值。

条件:这需要通过Python中的Dictionary来实现。

【问题讨论】:

    标签: python python-3.x dictionary key-value


    【解决方案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]}")
    

    【讨论】:

    • 我看到你已经回答了你自己的问题。您正在以最糟糕的方式找到字典的键和值......
    • 更简单的方法更受欢迎。你可以发布你的答案。 @tomjn
    • 只要print(d["Name1"])知道密钥,就不需要遍历整个字典
    • 工作得很好。还有什么方法可以将类似于strip 的函数应用于整数值?我有一个 IP,只希望在第三个 . 之后输出
    【解决方案2】:

    你可以的

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

    那会输出

    Value1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      相关资源
      最近更新 更多