Python foreach dict key

Python Iterate Over A Dictionary

How to iterate Python Dictionary using For loop? You can iterate a dictionary in python over keys, iterate over the key and the value, using the lambda function e.t.c. In this article, I will explain what is Dictionary ? its usage, and how to iterate through for loop with several examples.

Quick Examples Iterate Over a Dictionary

Following are quick examples of how to loop through a python dictionary using for loop.

 # Quick Examples # Example 1: Loop through by Dict Keys technology= for x in technology: print(x) # Example 2: Loop through by Key and Value technology= for key, value in technology.items(): print(key, value) # Example 3: Use key to get the Value technology= for key in technology: print(key,technologyPython foreach dict key) # Example 4: Use dict.keys() & dict.values() technology= for key in technology.keys(): print('Key: '+ key) for value in technology.values(): print('Value: '+value) # Example 5: Using for loop through dictionary to get index mydict = for i in mydict: print(i,mydict[i]) # Example 6: Using lambda function to iterate over a dictionary my_squares = my_cubes = list(map(lambda key: key**3, my_squares.keys())) print(my_cubes) # Example 7: Iterate dictionary using dictionary comprehension mydict = newdict = print(newdict) 

1. What is a Dictionary?

Python dictionary also known as dict is an important data structure that is used to store elements in key-value pairs. Each entry in the dictionary is in the form of key-value pairs. A dictionary is a collection of elements that is unordered, mutable, and does not allow duplicates in keys. Dictionary values should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

Читайте также:  Javascript class constructor async

Another important feature of dictionaries is that they are mutable data types, so, that you can be added, deleted, and updated their key-value pairs from the dictionary.

Dictionary Key – As I mentioned earlier, Dictionary doesn’t allow duplicated keys and keys must be of immutable type(such as string, number, tuple). in case, you add duplicates, it overrides the existing keys of the dictionary .

Dictionary Value – The values can be of any type of object and can be allowed duplicates. To get a value from a Python Dictionary you have to iterate over keys.

1.1 Create a Dictionary

 # Create dictionary mydict = < "course": "python", "fee": 4000, "duration": "60 days" >print(mydict) # Output:

As you see keys of the mydict are course , fee , duration . The values of the mydict are python , 4000 , 60 days .

2. Iterate Over Dictionary Keys

Use for loop in order to iterate a python dictionary over keys, by default when you use for loop with dict, it returns a key from the dict for each iteration.

 # Loop through by Dict Keys technology= for x in technology: print(x) 

Yields below output. Notice that it just displayed the keys from the dict.

 # Output: Course Fee Duration 

3. Loop through by Key and Value using dict.items()

Use dict. items() to return a view object that gives a list of dictionary’s (key, value) tuple pairs. so, that You can iterate through tuple to get the dictionary key and value.

 # Loop through by Key and Value technology= for key, value in technology.items(): print(key, value) 
 # Output: Course python Fee 4000 Duration 60 days 

4. Use Key to get the Value

Use dictPython foreach dict key to get the value of the key.

 # Use key to get the Value technology= for key in technology: print(key,technologyPython foreach dict key) 
 # Output: Course python Fee 4000 Duration 60 days 

5. Use dict.keys() & dict.values()

You can also get dict.keys() to iterate over each key, similarly, you can get the dict.values() to iterate each value in python dictionary.

 # Use dict.keys() & dict.values() technology= for key in technology.keys(): print('Key: '+ key) for value in technology.values(): print('Value: '+value) 
 # Output: Key: Course Key: Fee Key: Duration Value: python Value: 4000 Value: 60 days 

6. Iterate Through Dictionary With Index

we can also iterate through the dictionary using the index of the items, which is similar to iterating over the dictionary without using the methods such as keys() , values() , or items() .

 Using for loop through dictionary to get index mydict = for i in mydict: print(i,mydict[i]) 
 # Output: course 1 fee 2 duration 3 

7. Iterate Through Dictionary Using Lambda Function

Python lambda function is an anonymous function that can be used to loop through a dictionary.

7.1 Syntax

 # Lambda Syntax lambda arguments: expression 

Using the lambda function along with a Python map() function we can iterate over a dictionary easily.

 # Using lambda function to iterate over a dictionary my_squares = my_cubes = list(map(lambda key: key**3, my_squares.keys())) print(my_cubes) #Outputs [8, 27, 64, 125] 

From the above code, we have a lambda function lambda key: key**3 and my_squares.keys() are parameters to the map() function. This will apply the function (key**3) to each key in the dictionary.

8. Iterate over a Python Dictionary using dictionary comprehension

Python dictionary comprehension is an elegant and concise way to create dictionaries using iterables. however, it is the same as a list comprehension but the only difference is syntax due to the structure of dictionaries.

8.1 Syntax Of Dictionary Comprehension

 # Syntax of the dictionary comprehension

8.2 Iterate Dictionary Using Dictionary Comprehension

 # Iterate dictionary using dictionary comprehension mydict = newdict = print(newdict) # Outputs:

In dictionary comprehension, we have iterated through the dictionary using the items() method, which can be accessed both key and value of the Python dictionary.

9. Conclusion

In this article, I have explained the python dictionary, how to create it and how to iterate over using for loop. You can iterate through a python dictionary by keys and by key and value. Also, I have used the lambda function along with map() and used dictionary comprehension to iterate through the dictionary and apply a function to each item in the dictionary.

References

You may also like reading:

Источник

Iterate dictionary (key and value) with for loop in Python

In Python, to iterate through a dictionary ( dict ) with a for loop, use the keys() , values() , and items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() .

Consider the following dictionary as an example:

You can iterate keys by directly using the dictionary object in a for loop.

for k in d: print(k) # key1 # key2 # key3 

See the following article for the basics of for loops in Python.

Iterate dictionary keys: keys()

As mentioned above, you can iterate dictionary keys by directly using the dictionary object, but you can also use keys() . The result is the same, but keys() may clarify the intent to the reader of the code.

for k in d.keys(): print(k) # key1 # key2 # key3 

The keys() method returns dict_keys , which can be converted to a list with list() .

keys = d.keys() print(keys) print(type(keys)) # dict_keys(['key1', 'key2', 'key3']) # k_list = list(d.keys()) print(k_list) print(type(k_list)) # ['key1', 'key2', 'key3'] # 

You can use dict_keys to perform set operations. See the following article for details.

Iterate dictionary values: values()

To iterate dictionary values, use the values() method.

for v in d.values(): print(v) # 1 # 2 # 3 

The values() method returns dict_values , which can be converted to a list with list() .

values = d.values() print(values) print(type(values)) # dict_values([1, 2, 3]) # v_list = list(d.values()) print(v_list) print(type(v_list)) # [1, 2, 3] # 

Iterate dictionary key-value pairs: items()

To iterate dictionary key-value pairs, use the items() method.

for k, v in d.items(): print(k, v) # key1 1 # key2 2 # key3 3 

You can also receive the key-value pairs as a tuple of (key, value) :

for t in d.items(): print(t) print(type(t)) print(t[0]) print(t[1]) print('---') # ('key1', 1) # # key1 # 1 # --- # ('key2', 2) # # key2 # 2 # --- # ('key3', 3) # # key3 # 3 # --- 

The items() method returns dict_items , which can be converted to a list with list() .

items = d.items() print(items) print(type(items)) # dict_items([('key1', 1), ('key2', 2), ('key3', 3)]) # i_list = list(d.items()) print(i_list) print(type(i_list)) # [('key1', 1), ('key2', 2), ('key3', 3)] # print(i_list[0]) print(type(i_list[0])) # ('key1', 1) # 

You can also use dict_items to perform set operations. See the following article for details.

  • Unpack and pass list, tuple, dict to function arguments in Python
  • Merge multiple dictionaries and add items to a dictionary in Python
  • Swap dictionary keys and values in Python
  • Get value from dictionary by key with get() in Python
  • Get maximum/minimum values and keys in Python dictionaries
  • Add an item if the key does not exist in dict with setdefault in Python
  • Create a dictionary in Python (<>, dict(), dict comprehensions)
  • Sort a list of dictionaries by the value of the specific key in Python
  • Change dictionary key in Python
  • Get key from value in dictionary in Python
  • Remove an item from a dictionary in Python (clear, pop, popitem, del)
  • Pretty-print with pprint in Python
  • Check if key/value exists in dictionary in Python
  • Set operations on multiple dictionary keys in Python
  • Extract specific key values from a list of dictionaries in Python

Источник

Оцените статью