How to Iterate Over a Dictionary

Iterating over dictionaries using 'for' loops

key is just a variable name.

for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 3.x:

for key, value in d.items():

For Python 2.x:

for key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

How to iterate over a dictionary?

foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}

How to iterate through a nested dict?

As the requested output, the code goes like this

    d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

for k1,v1 in d.iteritems(): # the basic way
temp = ""
temp+=k1
for k2,v2 in v1.iteritems():
temp = temp+" "+str(k2)+" "+str(v2)
print temp

In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

Hope this helps :)

how to iterate over items in dictionary using while loop?

You can iterate the items of a dictionary using iter and next with a while loop. This is almost the same process as how a for loop would perform the iteration in the background on any iterable.

  • https://docs.python.org/3/library/functions.html
  • https://docs.python.org/3/library/stdtypes.html#iterator-types

Code:

user_info = {
"username" : "Hansana123",
"password" : "1234",
"user_id" : 3456,
"reg_date" : "Nov 19"
}

print("Using for loop...")
for key, value in user_info.items():
print(key, "=", value)

print()

print("Using while loop...")
it_dict = iter(user_info.items())
while key_value := next(it_dict, None):
print(key_value[0], "=", key_value[1])

Output:

Using for loop...
username = Hansana123
password = 1234
user_id = 3456
reg_date = Nov 19

Using while loop...
username = Hansana123
password = 1234
user_id = 3456
reg_date = Nov 19

Iterate through a dictionary and create new dictionary from multiple dictionaries

You can loop through key value pair in dictionary using for loop and using Update method you can add key value pair from dict2 to dict1.

The update() method inserts the specified items to the dictionary.

The specified items can be a dictionary, or an iterable object with key value pairs.

 for k,v in dict1.items():
for a, b in v.items():
for x , y in dict2['fields'].items():
dict1[k][a].update({x : y})
print(dict1)

Iterating over dictionary in Python and using each value

Use for loop for iteration.

dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
print(key+" "+ str(value))

for key in dict:
print(key+ " "+str(dict[key]))

The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary using the key.

How to iterate through dictionary of dictionaries in python

First rename your variable dict to d.

This is not dictionary of dictionary. This is dictionary containing tuples as key, and values.

for k, v in d.items():
a = k[1]
b = v[1]
print(a/b)

How to iterate (keys, values) in JavaScript?

tl;dr

  1. In ECMAScript 2017, just call Object.entries(yourObj).
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 5, it is not possible.

ECMAScript 2017

ECMAScript 2017 introduced a new Object.entries function. You can use this to iterate the object as you wanted.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};

for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}

Output

a 1
b 2
c 3


ECMAScript 2015

In ECMAScript 2015, there is not Object.entries but you can use Map objects instead and iterate over them with Map.prototype.entries. Quoting the example from that page,

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

var mapIter = myMap.entries();

console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]

Or iterate with for..of, like this

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
console.log(entry);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Or

for (const [key, value] of myMap.entries()) {
console.log(key, value);
}

Output

0 foo
1 bar
{} baz


ECMAScript 5:

No, it's not possible with objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}

Note: The if condition above is necessary only if you want to iterate over the properties which are the dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});

Python - Iterate the keys and values from the dictionary

You can use this code snippet.

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
print(key)

#To Iterate over the values
for value in dictionary.values():
print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
print(key,'\t', value)


Related Topics



Leave a reply



Submit