Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating over shared keys in two dictionaries

Tags:

python

I have two dicts. They share some keys. I'd like to iterate over those shared keys. Here are three ways to do it.

x={1:'a', 2:'b', 3:'c'}
y={2:'beta', 3:'gamma', 4:'delta'}

for n in (key for key in x if key in y):
    print(n)

for n in x:
    if n in y:
        print(n)

for n in x:
    if n not in y:
        continue
    print(n)

The first one looks like it will be hard to read in the future.

The second will have lots of indenting in the loop.

The third uses continue which I find to make code a bit harder to follow.

Is there a standard for what I should be using? And is it one of these three?

like image 893
Joel Avatar asked Mar 19 '15 07:03

Joel


People also ask

Can you iterate over dictionary keys?

To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.

How do I combine two dictionary keys?

The simplest way to merge two dictionaries in python is by using the unpack operator(**). By applying the "**" operator to the dictionary, it expands its content being the collection of key-value pairs.

Can two dictionary keys have the same value?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

How do I iterate through a dictionary only over the keys?

In order to iterate only over keys you need to call keys () method that returns a new view of the dictionary’s keys. In order to iterate over the values of the dictionary, you simply need to call values () method that returns a new view containing dictionary’s values.

How to iterate through a dictionary in Python using for loop?

To iterate through a dictionary in Python by using .keys (), you just need to call .keys () in the header of a for loop: When you call .keys () on a_dict, you get a view of keys.

How to access two dictionaries at the same time?

A safer solution is to choose one dictionary, d in this case, to get the keys from, then use those to access the second dictionary: This isn't more complex than the other answers, and is explicit about which keys are being accessed.

Are Python dictionaries iterated in the same order?

In Python 3.6 and beyond, the keys and values of a dictionary are iterated over in the same order in which they were created. However, this behavior may vary across different Python versions, and it depends on the dictionary’s history of insertions and deletions.


Video Answer


2 Answers

The best approach depends on what version of Python you're using. They all involve using the & operator for set intersection.

  • 3.0+ dict.keys() approach
  • 2.7+ dict.viewkeys() approach
  • 2.3+ set approach

dict.keys() -- 3.0+

In Python 3, dict.keys() returns a dict_keys object which overrides the & operator[1]:

x={1:'a', 2:'b', 3:'c'}
y={2:'beta', 3:'gamma', 4:'delta'}

for k in x.keys() & y.keys():
    print(k, x[k], y[k])

Output:

2 b beta
3 c gamma

But in Python 2, this will give you a TypeError:

Traceback (most recent call last):
    for k in x.keys() & y.keys():
TypeError: unsupported operand type(s) for &: 'list' and 'list'

dict.viewkeys() -- 2.7+

Don't fret, however! This functionality was backported to Python in 2.7, but under a different name (so as not to break existing code), dict.viewkeys():

for k in x.viewkeys() & y.viewkeys():
    print k, x[k], y[k]

(Same output)

With sets -- 2.3+

Since 2.3 you're able to use sets, and the intersection (&) operator.

s & t: new set with elements common to s and t

For example:

for k in set(x) & set(y):
    print k, x[k], y[k]

(Same output)

Here, however, you're duplicating the space that the keys take up (once in the dictionary, serving as keys, and once again in a completely separate set)

[1] PEP-3106 Revamping dict.keys(), .values() and .items()

like image 101
jedwards Avatar answered Nov 06 '22 16:11

jedwards


If you want to avoid indentation (though, really, it doesn't look like much) and want something clearer than the first one, you could use a set intersection:

for k in x.keys() & y.keys():
    print k

& is the intersection operator, making sure you iterate over shared keys only. If you want to iterate over all keys instead, use x.keys() | y.keys()

like image 37
vermillon Avatar answered Nov 06 '22 18:11

vermillon