Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a key without value from a dictionary that has multiple keys [closed]

I'm sure there is a simple answer just have not been able to find it directly.

If I have a dictionary stored in a variable, I would like to pull out a single key and print it to the console without the attached value. Also it would be helpful to see how to get the value without the key, and both the key and value together.

So,

pocket = {"change":14,"lint":"handfull"}

How would I proceed to print just change; print just the value in change; and print change and its value together but without the brackets, comma and quotations?

like image 474
humbledCoder Avatar asked Dec 02 '25 05:12

humbledCoder


2 Answers

To have all the keys:

print(dictionary.keys())

All the values:

print(dictionary.values())

All items:

print(dictionary.items())

To print them one by one, loop through it:

for key in dictionary.keys():
    print("Key: ", key)
for value in dictionary.values():
    print("Value: ", value)
for k, v in dictionary.items():
    print("Key: ", k)
    print("Value: ", v)

To understand dictionaries better, click the docs!

Well, hope this helps!

like image 145
aIKid Avatar answered Dec 03 '25 18:12

aIKid


To just print a single specific value from a dictionary, change in your example, you have to know the key.

To just print the "first" value in a dictionary is possible but you shouldn't ever use it as it is unpredictable.

To print the value only:

pocket.get("change", "penniless") # if the key is missing gives the default

or

pocket["change"]  # can fail

Since you must always know the key to talk reliably about a single entry you can always print the key or the pair.

like image 28
Steve Barnes Avatar answered Dec 03 '25 20:12

Steve Barnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!