How to Print Specific Key Value from a Dictionary

How to print Specific key value from a dictionary?

It's too late but none of the answer mentioned about dict.get() method

>>> print(fruit.get('kiwi'))
2.0

In dict.get() method you can also pass default value if key not exist in the dictionary it will return default value. If default value is not specified then it will return None.

>>> print(fruit.get('cherry', 99))
99

fruit dictionary doesn't have key named cherry so dict.get() method returns default value 99

How to print specific key:value pairs from a pickled dictionary

for countryDict in countries:
print(countryDict[choice])

Should do the trick. The variable that you have defined as countries is actually a tuple of dictionaries (dictCont, dictPop, dictArea, dictDensity). So the for loop iterates over each of those dicts and then gets the country of choice from them. In this case, countries is a poor name choice. I had read it and assumed it was a single dictionary with an array of values, as I was too lazy to read your second code block. As a rule of thumb, always assume other coders are lazy. Trust me.

Print specific keys and values from a deep nested dictionary in python 3.X

Use recursion and isinstance:

my_nested_dict = {"global": {"peers": {"15.1.1.1": {"remote_id": "15.1.1.1", "address_family": {"ipv4": {"sent_prefixes": 1, "received_prefixes": 4, "accepted_prefixes": 4}}, "remote_as": 65002, "uptime": 13002, "is_enabled": True, "is_up": True, "description": "== R3 BGP Neighbor ==", "local_as": 65002}}, "router_id": "15.1.1.2"}}

filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

def seek_keys(d, key_list):
for k, v in d.items():
if k in key_list:
if isinstance(v, dict):
print(k + ": " + list(v.keys())[0])
else:
print(k + ": " + str(v))
if isinstance(v, dict):
seek_keys(v, key_list)

seek_keys(my_nested_dict, filtered_list)

Note: There is a built in assumption here that if you ever want the "value" from a key whose value is another dictionary, you get the first key.

Print specific value index from key in dictionary

You have a dictionary with a key:value pair where the value is a list.

To reference values within this list, you do your normal dictionary reference, ie

 dict['chmi']

But you need to add a way to manipulate your list. You can use any of the list methods, or just use a list slice, ie

dict['chmi'][0] 

will return the first element of the list referenced by key chmi. You can use

dict['chmi'][dict['chmi'].index('48680')]

to reference the 48680 element. What I am doing here is calling the

list.index(ele) 

method, which returns the index of your element, then I am referencing the element by using a slice.

How to print a specific key from a dictionary of dictionary in python

def book_finder():
lent_list = [{"Larry" : "Harry Potter and the chamber of secrets"}, {"Ronald" : "marvel iron man comic"}, {"Bernald" : "Hardy boys adventure Peril at Granite Peak"}]
for dic in lent_list:
for value in dic.values():
print(value)
book_name = input("Enter a book name to find ")

value = ""
for dic in lent_list:
for key,value in dic.items():
if book_name == value:
value = (f"{key} took the book {value}")
return value

value = "Sorry book not available."
return value


print(book_finder())

How to print specific key values from a list of dictionaries in Python?

Possible solution is following:

employees = [
{'name': 'Tanya', 'age': 20, 'birthday': '1990-03-10',
'job': 'Back-end Engineer', 'address': {'city': 'New York', 'country': 'USA'}},
{'name': 'Tim', 'age': 35, 'birthday': '1985-02-21', 'job': 'Developer', 'address': {'city': 'Sydney', 'country': 'Australia'}}]

for employee in employees:
print(f"{employee['name']}, {employee['job']}, {employee['address']['city']}")

Prints

Tanya, Back-end Engineer, New York
Tim, Developer, Sydney

How to print a dictionary's key?

A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

for key, value in mydic.iteritems() :
print key, value

Python 3 version:

for key, value in mydic.items() :
print (key, value)

So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.

Print specific values and keys in a dictionary on separate lines in python3

You can do a simple iteration over the dict and print the key, value if the key is present in your needed keys.

my_dictionary = {'vendor': 'Maker', 'hostname': 'PC1',
'os_version': 'OSv1', 'uptime': 7260,
'serial_number': '9NJFB4', 'model': 'Iv2', 'fqdn': 'PC1.lab.local'}

needed_keys = ['fqdn', 'serial_number', 'model', 'uptime']

for key, val in my_dictionary.items():
if key in needed_keys:
print(f'{key} : {val}')

# Output

uptime : 7260
serial_number : 9NJFB4
model : Iv2
fqdn : PC1.lab.local

If the python version is older than 3.6 which don't have support for f-strings use the following code with format to print the key-value

my_dictionary = {'vendor': 'Maker', 'hostname': 'PC1',
'os_version': 'OSv1', 'uptime': 7260,
'serial_number': '9NJFB4', 'model': 'Iv2', 'fqdn': 'PC1.lab.local'}

needed_keys = ['fqdn', 'serial_number', 'model', 'uptime']

for key, val in my_dictionary.items():
if key in needed_keys:
print('{key} : {val}'.format(key=key, val=val))


Related Topics



Leave a reply



Submit