get dictionary value by key code example
Example 1: access dic by key c#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}
Example 2: python get value from dictionary
dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
dict.get('shape') #returns square
#You can also set a return value in case key doesn't exist (default is None)
dict.get('volume', 'The key was not found') #returns 'The key was not found'
Example 3: how to get value from key dict in python
# Get a value from a dictionary in python from a key
# Create dictionary
dictionary = {1:"Bob", 2:"Alice", 3:"Jack"}
# Retrieve value from key 2
entry = dictionary[2]
# >>> entry
# Alice