简体   繁体   中英

How to create a dictionary out of a list?

I have extracted a list of numbers from a word document to see which hour of a day gives us the most number of visits. I wanted to create a key number pair dictionary from the list of numbers.

These are the list of numbers with me

['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']

and my output should look somewhat like this

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

I'm not quite able to figure out what to next.

Thanks in advance.

Use Counter :

from collections import Counter

l = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10',
     '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']
result = Counter(l)

OUTPUT:

Counter({'09': 2,
         '18': 1,
         '16': 4,
         '15': 2,
         '14': 1,
         '11': 6,
         '10': 3,
         '07': 1,
         '06': 1,
         '04': 3,
         '19': 1,
         '17': 2})

To get the most common element you can use:

most_common_element = result.most_common(1)[0] # prints `11`
     z = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16']
        # trans list to dict
        d = dict((int(i), z.count(i)) for i in z)
        # sort dict by key
        d = dict(sorted(d.items()))
        print(d)
        OUTPUT:
 {4: 3,
     6: 1,
     7: 1,
     9: 2,
     10: 3,
     11: 6,
     14: 1,
     15: 2,
     16: 4,
     17: 2,
     18: 1,
     19: 1}

This is what you want

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