Python equivalent of zip for dictionaries

2024/11/19 18:57:57

If I have these two lists:

la = [1, 2, 3]
lb = [4, 5, 6]

I can iterate over them as follows:

for i in range(min(len(la), len(lb))):print la[i], lb[i]

Or more pythonically

for a, b in zip(la, lb):print a, b

What if I have two dictionaries?

da = {'a': 1, 'b': 2, 'c': 3}
db = {'a': 4, 'b': 5, 'c': 6}

Again, I can iterate manually:

for key in set(da.keys()) & set(db.keys()):print key, da[key], db[key]

Is there some builtin method that allows me to iterate as follows?

for key, value_a, value_b in common_entries(da, db):print key, value_a, value_b 
Answer

There is no built-in function or method that can do this. However, you could easily define your own.

def common_entries(*dcts):if not dcts:returnfor i in set(dcts[0]).intersection(*dcts[1:]):yield (i,) + tuple(d[i] for d in dcts)

This builds on the "manual method" you provide, but, like zip, can be used for any number of dictionaries.

>>> da = {'a': 1, 'b': 2, 'c': 3}
>>> db = {'a': 4, 'b': 5, 'c': 6}
>>> list(common_entries(da, db))
[('c', 3, 6), ('b', 2, 5), ('a', 1, 4)]

When only one dictionary is provided as an argument, it essentially returns dct.items().

>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]

With no dictionaries, it returns an empty generator (just like zip())

>>> list(common_entries())
[]
https://en.xdnf.cn/q/26323.html

Related Q&A

Can I prevent fabric from prompting me for a sudo password?

I am using Fabric to run commands on a remote server. The user with which I connect on that server has some sudo privileges, and does not require a password to use these privileges. When SSHing into th…

Managing connection to redis from Python

Im using redis-py in my python application to store simple variables or lists of variables in a Redis database, so I thought it would be better to create a connection to the redis server every time I n…

Writing a Python extension in Go (Golang)

I currently use Cython to link C and Python, and get speedup in slow bits of python code. However, Id like to use goroutines to implement a really slow (and very parallelizable) bit of code, but it mus…

Non-global middleware in Django

In Django there is a settings file that defines the middleware to be run on each request. This middleware setting is global. Is there a way to specify a set of middleware on a per-view basis? I wan…

I want to replace single quotes with double quotes in a list

So I am making a program that takes a text file, breaks it into words, then writes the list to a new text file.The issue I am having is I need the strings in the list to be with double quotes not singl…

How can I get stub files for `matplotlib`, `numpy`, `scipy`, `pandas`, etc.?

I know that the stub files for built-in Python library for type checking and static analysis come with mypy or PyCharm installation. How can I get stub files for matplotlib, numpy, scipy, pandas, etc.?…

Pipfile.lock out of date

Im trying to deploy a large django project to heroku. I installed Heroku CLI, logged in, created an app and ran:git push heroku masterI have a Pipfile and requirements.txt already set up. I added a run…

Can a simple difference in Python3 variable names alter the way code runs? [duplicate]

This question already has answers here:Python attributeError on __del__(2 answers)Closed 9 years ago.This code...class Person:num_of_people = 0def __init__(self, name):self.name = namePerson.num_of_peo…

Easy way to check that a variable is defined in python? [duplicate]

This question already has answers here:How do I check if a variable exists?(15 answers)Closed 10 years ago.Is there any way to check if a variable (class member or standalone) with specified name is d…

Adding install_requires to setup.py when making a python package

To make a python package, in setup.py, I have the following: setup(name=TowelStuff,version=0.1.0,author=J. Random Hacker,author_email=[email protected],packages=[towelstuff, towelstuff.test],scripts=[b…