简体   繁体   中英

duplicating values in a certain way inside a list inside a dictionary

I am new to programming as well as python, and I have a question that I have not found an answer for on the internet. I was wondering if any of you geniuses will be able to help me out.

I have a dictionary and in the dictionary, the keys are strings and the values are lists. I was wondering if it was possible to turn this dictionary:

dict1 = {'a':(1, 4, 7), 'b':(2, 5, 8), 'c':(3, 6, 9)}

have each value duplicated once into this format so the duplicates are next to the originals:

dict1 = {'a':(1, 1, 4, 4, 7, 7), 'b':(2, 2, 5, 5, 8, 8), 'c':(3, 3, 6, 6, 9, 9)}

You can use a dictionary comprehension :

>>> dict1 = {'a':(1, 4, 7), 'b':(2, 5, 8), 'c':(3, 6, 9)}
>>> {x:tuple(z for z in y for _ in xrange(2)) for x,y in dict1.iteritems()}
{'a': (1, 1, 4, 4, 7, 7), 'c': (3, 3, 6, 6, 9, 9), 'b': (2, 2, 5, 5, 8, 8)}
>>>

Note however that the above code was built in Python 2.7. If you are on Python 3.x, you will want this:

>>> dict1 = {'a':(1, 4, 7), 'b':(2, 5, 8), 'c':(3, 6, 9)}
>>> {x:tuple(z for z in y for _ in range(2)) for x,y in dict1.items()}
{'a': (1, 1, 4, 4, 7, 7), 'c': (3, 3, 6, 6, 9, 9), 'b': (2, 2, 5, 5, 8, 8)}
>>>

Also, in both solutions, the order of the keys cannot be guaranteed. That is just a result of the way dictionaries are implemented in Python.

Firstly, your values are tuples, not lists. The difference is subtle, but the relevant part is that tuples are not mutable

So, let's first transform what you have to a list-valued dictionary, and then solve your problem

>>> dict1 = {'a':(1, 4, 7), 'b':(2, 5, 8), 'c':(3, 6, 9)}
>>> dict1 = {k:list(v) for k,v in dict1.items()}
>>> dict1
{'b': [2, 5, 8], 'c': [3, 6, 9], 'a': [1, 4, 7]}
>>> answer = {k:list(itertools.chain.from_iterable(zip(v,v))) for k,v in dict1.items()}
>>> answer
{'b': [2, 2, 5, 5, 8, 8], 'c': [3, 3, 6, 6, 9, 9], 'a': [1, 1, 4, 4, 7, 7]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM