xxxxxxxxxx
# list of keys
my_keys = ['apple', 'banana', 'pear']
# list of values
my_values = ['red', 'yellow', 'green']
# create dictionary
my_dict = {}
# match the corresponding keys to values
for i in range(len(my_keys)):
my_dict[my_keys[i]] = my_values[i]
# output
# my_dict = {'apple': 'red',
# 'banana': 'yellow',
# 'pear': 'green'}
xxxxxxxxxx
# To get all the keys of a dictionary as a list, see below
newdict = {1:0, 2:0, 3:0}
list(newdict)
# Output:
# [1, 2, 3]
xxxxxxxxxx
>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]
"""
In [1]: newdict = {1:0, 2:0, 3:0}
In [2]: %timeit [*newdict]
107 ns ± 5.42 ns per loop
In [3]: %timeit list(newdict)
144 ns ± 7.99 ns per loop
In [4]: %timeit [k for k in newdict]
257 ns ± 21.6 ns per loop
"""
>>> list(newdict.keys()) # don't do this.
xxxxxxxxxx
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
print(keys_list)
xxxxxxxxxx
# Driver program
dict = {1: 'Geeks', 2: 'for', 3: 'geeks'}
print(dict.keys())
xxxxxxxxxx
List<string> keyList = new List<string>(this.yourDictionary.Keys);
xxxxxxxxxx
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (string key in data.Keys) // look carefully Keys is used with "s" in it
{
Console.WriteLine(key);
}