简体   繁体   中英

How to save key corresponding to every value of a dictionary in a list in Python?

I have a dictionary which has only two keys: "f" and "m". Both these keys have 1000 unique values in it. Therefore total 2000 values corresponding to "f" and "m"

How can create a list of length 2000 having key's stored in it ie "f" and "m" for all 2000 values of dict ?

Edit: I wanted output to be a list like ['f','f','f',........(1000 "f" in list ),'m','m'.......(1000 "m" in list)]

Let's create/simulate a dictionary 'foo' containing 2 keys 'f' and 'm'. The value stored against each of these keys is a list of 1000 elements.

>>> foo = {'f': ['x']*1000, 'm': ['y']*1000}
>>> len(foo['f'])
1000
>>> len(foo['m'])
1000
>>> 

Now, let's initialize an empty list 'bar' to store the desired output.

>>> bar = []
>>> 

A list can be extended to include elements from other list in the original list. Let's use this to extend 'bar' to contain as many 'f' as the number of elements in foo['f'].

>>> bar.extend(['f']*len(foo['f']))
>>> 

Repeat the same for foo['m']

>>> bar.extend(['m']*len(foo['m']))
>>> 

Now, 'bar' is a list of 2000 elements - first 1000 elements are 'f' and next 1000 elements are 'm'. Verifying the values against indices 0, 999 (first 1000 elements) and 1000, 1999 (remaining 1000 elements) prove the same.

>>> len(bar)
2000
>>> bar[0]
'f'
>>> bar[999]
'f'
>>> bar[1000]
'm'
>>> bar[1999]
'm'
>>>

do you want something like this ?

dummy_dict={'f':[1,2,3,4,5,6],'m':[14,13,11,43,11,2,11,1,4,34]}

print([key for key,value in dummy_dict.items() for _ in range(len(value))])

output :

['f', 'f', 'f', 'f', 'f', 'f', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm']

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