Capriles - 1 year ago 61

Python Question

I need to extract very specific key-value pairs from a dictionary. The keys are whole numbers and the values repeat for a certain number of keys, which varies.

I must extract the last key-value pair for the repeated value. So, in this case, I need to extract the key-value pairs:

`42: ['e ']`

85: ['dis ']

88: ['d ']

95: ['e ']

The number of times a certain value appears is random. A value may appear again later, as is the present case with the value ['e '], and so I need to extract it twice.

This is the example I'm using here for the type of dictonary I'm dealing with:

`notes_dict = {`

0: ['e '],

1: ['e '],

2: ['e '],

3: ['e '],

#(...)

40: ['e '],

41: ['e '],

42: ['e '],

43: ['dis '],

44: ['dis '],

45: ['dis '],

#(...)

83: ['dis '],

84: ['dis '],

85: ['dis '],

86: ['d '],

87: ['d '],

88: ['d '],

89: ['e '],

90: ['e '],

91: ['e '],

92: ['e '],

93: ['e '],

94: ['e '],

95: ['e ']

}

Idea behind this: this dictionary contais information about which musical note is being played at a given time. I need to make this process automatic in order to try and plot a very simplified sheet music.

Answer Source

This might work for you:

```
from itertools import groupby
notes_dict = {
0: ['e '],
1: ['e '],
2: ['e '],
3: ['e '],
40: ['e '],
41: ['e '],
42: ['e '],
43: ['dis '],
44: ['dis '],
45: ['dis '],
83: ['dis '],
84: ['dis '],
85: ['dis '],
86: ['d '],
87: ['d '],
88: ['d '],
89: ['e '],
90: ['e '],
91: ['e '],
92: ['e '],
93: ['e '],
94: ['e '],
95: ['e ']
}
for k, g in groupby(sorted(notes_dict),
key=notes_dict.get):
print '{}: {}'.format(list(g)[-1], k)
```