Bogota
Bogota

Reputation: 391

Print the value of specific key from Dictionary in Python

I have Input.txt and the contents of this file are:

Name1=Value1
Name2=Value2
Name3=Value3

Desired output: get the value of key==Name1.

Condition: This needs to be implemented by Dictionary in Python.

Upvotes: 0

Views: 88

Answers (2)

Leo Arad
Leo Arad

Reputation: 4472

You can do

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

That will output

Value1

Upvotes: 0

Bogota
Bogota

Reputation: 391

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]}")

Upvotes: 2

Related Questions