-3

I have a dict like this:

{'ABC': array([
         [ 0.,1.,2.],
         [ 3.,4.,5.],
         [ 6.,7.,8.]]),
        array([
         [ 0.,1.,2.],
         [ 3.,4.,5.],
         [ 6.,7.,8.]])
 'DEF': array([
         [ 0.,1.,2.],
         [ 3.,4.,5.],
         [ 6.,7.,8.]]),
        array([
         [ 0.,1.,2.],
         [ 3.,4.,5.],
         [ 6.,7.,8.]])}

and I want to have a new like this:

['ABC','ABC','DEF','DEF']

with each key corresponding to each element in the value and get duplicated.

I tried:

[(key,val) for (key,val) in d1.items()]

but the key didn't get duplicated

Ray
  • 59
  • 5
  • 1
    Got some history homework for us to do as well? :) You need to show you've attempted to solve this problem first - Google will help here "Extract dict keys python" and you'll get this https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python – Trent Feb 25 '19 at 05:28
  • 3
    Possible duplicate of [How to return dictionary keys as a list in Python?](https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python) – Trent Feb 25 '19 at 05:29
  • I'm new to Python. I know how to extract key and values but didn't find a way to put them together. – Ray Feb 25 '19 at 05:43

1 Answers1

0

Your dictionary has some invalid syntax, but I think you want this:

[key for key, val in d1.items() for _ in val]

For instance:

d1 = {'ABC': [1, 2, 3], 'DEF': [4, 5], 'GHI': [6]}
print([key for key, val in d1.items() for _ in val])
# ['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'GHI']
iz_
  • 15,923
  • 3
  • 25
  • 40