How to create key value dictionary in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main() {
        Dictionary<string, int> dict = new Dictionary<string, int>();

        dict["csharp"] = 1;
        dict["c"] = 4;
        dict["java"] = 6;
        
        dict.Add("python", 9);
            
        Console.WriteLine("key values:");
        foreach (KeyValuePair<string, int> kvp in dict) {
                Console.WriteLine(kvp.Key + " - " + kvp.Value);
        }

        Console.WriteLine("\nkeys:");
        foreach (string key in dict.Keys) {
            Console.WriteLine(key);
        }
            
        Console.WriteLine("\nvalues:");
        foreach (int val in dict.Values) {
            Console.WriteLine(val.ToString());
        }
    }
}




/*
run:

key values:
csharp - 1
c - 4
java - 6
python - 9

keys:
csharp
c
java
python

values:
1
4
6
9

*/

 



answered Dec 10, 2022 by avibootz
edited Dec 10, 2022 by avibootz

Related questions

5 answers 222 views
1 answer 138 views
1 answer 178 views
178 views asked Oct 17, 2018 by avibootz
1 answer 134 views
...