0

I have a dict which I populate with data using setdefault method as follows:

if date not in call_dict:
    call_dict.setdefault(date, [0, 0]).append(0)
else:
    call_dict[date][0] += 1
    if x[12] != 'ANSWERED':
        call_dict[date][1] += 1
    call_dict[date][2] = 100*(call_dict[date][1]/call_dict[date][0])

At the end of this process I have a dict which is structured like this:

{'key' : value0, value1, value2}

Then I have to plot only key and value2 (as value2 is a function of the key) but I can't find the way to access this value. I tried myDict.values() but it did not work (as expected). I would really like to avoid creating another list/dict/anything because of script performance and also to achieve that I would still have to reach for the value2 which would solve my problem.

Any ideas how to solve this problem?

Sample values of dict:

{'08:23': [45, 17, 37.77777777777778], 
'08:24': [44, 15, 34.090909090909086], 
'08:25': [46, 24, 52.17391304347826], 
'08:48': [49, 19, 38.775510204081634],
7
  • Please provide sample dict data Jul 11, 2018 at 12:48
  • so you want to plot the pairs (key_i , value2_i ) ?
    – Yuca
    Jul 11, 2018 at 12:54
  • @Mr.J please check edited post
    – hikamare
    Jul 11, 2018 at 12:59
  • @GerardoFlores if by _i you mean: first, second, etc then yes :)
    – hikamare
    Jul 11, 2018 at 12:59
  • there's an issue with the sample values you provided. A dictionary print usualy looks like {'key0': [45, 17, 37], 'key1' : [44, 15, 34],..} So what you want to plot is (key0, 37), (key1, 34)?
    – Yuca
    Jul 11, 2018 at 13:05

1 Answer 1

3

You can get them from the dictionary with a list comprehension:

data = { "2018-07-01": [45, 17, 37.77777777777778], 
         "2018-07-02": [44, 15, 34.090909090909086], 
         "2018-07-03": [46, 24, 52.17391304347826], 
         "2018-07-04": [49, 19, 38.775510204081634]}


xy = [(x,data[x][2]) for x in data.keys()] # extract tuples of (date-key, 3rd value)

print(xy)

Output:

[('2018-07-01', 37.77777777777778), ('2018-07-02', 34.090909090909086), 
 ('2018-07-03', 52.17391304347826), ('2018-07-04', 38.775510204081634)]

If you need them for plotting you might want to do:

x,y = zip(*xy)
print(x)
print(y)

Output:

('2018-07-01', '2018-07-02', '2018-07-03', '2018-07-04')  # x
(37.77777777777778, 34.090909090909086, 52.17391304347826, 38.775510204081634)  # y

and supply those to your plotting library as x and y data.

Doku: zip(*iterables)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.