Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging dictionaries using a counter

I have the following dictionaries (example):

>>> x = {'a': 'foo', 'b': 'foobar'}
>>> y = {'c': 'barfoo', 'd': 'bar'}

I want to take the keys of each and make them the value of another dict, say z, such that the keys of z is an incremented counter, equal to the length of both the dicts.

>>> z = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

As you can notice, the keys of z is an incremented counter and the values are the keys of x and y.

How do I achieve this? I have tried various solutions and playing with zip, but none seem to work. Probably because I have to update the z dict in succession.

Any suggestions?

like image 432
user225312 Avatar asked Jan 25 '26 08:01

user225312


2 Answers

In [1]: import itertools
In [2]: x = {'a': 'foo', 'b': 'foobar'}
In [3]: y = {'c': 'barfoo', 'd': 'bar'}

In [4]: z = [key for key in itertools.chain(x, y)]

In [5]: z
Out[5]: ['a', 'b', 'c', 'd']

In [6]: dict(enumerate(z))
Out[6]: {0: 'a', 1: 'b', 2: 'c', 3: 'd'}

In [7]: dict(enumerate(z, 1))
Out[7]: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

If you want duplicate keys to occur only once, replace [4] with this:

z = set(key for key in itertools.chain(x, y))

Note that you also could do everything at once (for this example I've added 'a': 'meow' to y):

In [15]: dict(enumerate(set(key for key in itertools.chain(x, y)), 1))
Out[15]: {1: 'a', 2: 'c', 3: 'b', 4: 'd'}

In [16]: dict(enumerate((key for key in itertools.chain(x, y)), 1))
Out[16]: {1: 'a', 2: 'b', 3: 'a', 4: 'c', 5: 'd'}
like image 67
ThiefMaster Avatar answered Jan 26 '26 22:01

ThiefMaster


import itertools as it
{i+1:k for i,k in enumerate(it.chain(x,y))}
# {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Note that dict- (and related set-) comprehensions are new in v2.7+.

like image 32
mechanical_meat Avatar answered Jan 26 '26 22:01

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!