Python Forum
Converting a list to dictinary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting a list to dictinary
#1
Greetings to those that do not sleep! Wink

I kind of asked a similar question before (about counters).

I have a file:
PRQ09_PCX0161Host,DV1
PRQ09_PCX0170Host,PHQ
PRQ09_PCX0171Host,ATC
PRQ09_PCX0173Host,ATC
PRQ09_PCX0175Host,ATC
PRQ09_PCX0176Host,PHQ
PRQ09_PCX0179Host,DG2
PRQ09_PCX0180Host,TGP_H
PRQ09_PCX0183Host,PHQ
PRQ09_PCX0184Host,PHQ
PRQ09_PCX0280Host,TCP_H
PRQ09_PCX0380Host,TCP_H

I need to count similar items after the coma. You guys pointed me to use a "Counter" and it works great.
But now I want to convert a list that has all the lines from the file to a dictionary and use the "Counter" so I do not have to save data to a file and open it for counting elements.

Thank you.
Reply
#2
Can you show an example of what you're looking for? I can think of a few ways to convert the data in a list to data in a dict, but not sure how that would mesh with a Counter. What's the data you want to end up with?
Reply
#3
I'm processing some data and output goes to a file (see below)
I need to count all items after the coma.
file:
PRQ09_PCX0161Host,DV1
PRQ09_PCX0170Host,PHQ
PRQ09_PCX0171Host,ATC
PRQ09_PCX0173Host,ATC
PRQ09_PCX0175Host,ATC

I need to get the number of occurrences of 'DVI' ,'PHQ','ATC' and so on...
You guys helped me with the code that does that:
prdcs = []

with open (prod_BY_host, 'r') as pr_host :
    for lnf in pr_host :
        lnf=lnf.strip()
        host,prName = lnf.split(',')
        prdcs.append(prName)
        nn=Counter(prdcs) 
    #print(Counter(prdcs))
    nn =collections.Counter(prdcs)
    for key, value in nn.items():
        print(key, ':', value) 
But I do not want to save the data to a file and then open the file for counting items after the coma.
I thought I could store each line into the list and then convert it to a dictionary so I can use the code above to count items after the coma.
Thank you.
Reply
#4
"Convert to a dictionary" seems to be the bit that isn't necessary. You're starting with a list, and you want a count at the end. You can create a dictionary if you need it, but it isn't required for a counter.

The code you pasted is a little odd. You set nn each time you loop over the lines, then you set it again afterward. The assignment in the loop isn't doing anything and should be removed.

How does your data start? You mention "store each line into a list", so it sounds like even the list isn't the first thing. You could create the counter at the same time you gather the data and not have a list or a dictionary. But I'll ignore that for now and assume you have the list.

I had originally suggested
from collections import Counter
with open ("prdcs_file.txt", 'r') as pr_host :
    c = Counter(x.split(',')[1] for x in pr_host.read().splitlines())
 
print('\n'.join(f"{k}, {v}" for k,v in c.items()))
The pr_host.read().splitlines() part is turning the file into an iterator with each element one of the lines. A list is already an iterator. So if each element is one of the lines, you could just plop a list there.

from collections import Counter
prdcs = ["PRQ09_PCX0161Host,DV1",
        "PRQ09_PCX0170Host,PHQ",
        "PRQ09_PCX0171Host,ATC",
        "PRQ09_PCX0173Host,ATC",
        "PRQ09_PCX0175Host,ATC"]
c = Counter(x.split(',')[1] for x in prdcs)
print('\n'.join(f"{k}, {v}" for k,v in c.most_common()))
Output:
ATC, 3 DV1, 1 PHQ, 1
tester_V and buran like this post
Reply
#5
It works great! But it prints like this :
ATC,
3
DV1,
1
PHQ,
1
I tried different things but it still prints Keys and Vals on a new line...

Thank you!
Reply
#6
I fixed it. It does not look as clean as your code but it works.
for k,v in c.most_common() :
    vs =str(v)
    ks=k
    ks=ks.strip()
    line_out = ks+","+str(vs)
    print(f"{line_out}")
Thank you!
Reply
#7
Well here is a better version Wink
for k,v in c.most_common() :
    k=k.strip()
    line_out = ",".join([k,str(v)])
    print(f"{line_out}")
Reply
#8
Since line_out is already a string, f"{line_out}" is the same as line_out.

I think you are wrong about this:
Quote:It works great! But it prints like this :
ATC,
3
DV1,
1
PHQ,
1
I can believe that it prints like this:
Output:
ATC , 3 DV1 , 1 PHQ , 1
This output indicates that the code reading the file is leaving a linefeed character on the end of the the key (ATC\n, DV1\n, PHQ\n). You should remove the linefeeds when you read the file. This not only removes the extra linefeeds when printing results, but it results in dictionary keys without hidden characters.
tester_V likes this post
Reply
#9
I agree. I need to check my code and I'll do that.
Really appreciate your help!
Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting tkinter listbox into list BigSwiggy 6 3,606 Feb-07-2021, 02:01 PM
Last Post: BigSwiggy
  Converting list to variables Palves 1 1,761 Sep-18-2020, 05:43 PM
Last Post: stullis
  Trouble with converting list , dict to int values! faryad13 7 3,747 Sep-04-2020, 06:25 AM
Last Post: faryad13
  converting list of zero length to a matrix of 3*3 vp1989 2 1,924 May-20-2020, 07:46 PM
Last Post: deanhystad
  converting string object inside a list into an intiger bwdu 4 2,603 Mar-31-2020, 10:36 AM
Last Post: buran
  more list help converting paul41 3 2,432 Nov-25-2019, 07:59 AM
Last Post: perfringo
  Converting parts of a list to int for sorting menator01 2 2,226 Nov-03-2019, 03:00 PM
Last Post: menator01
  Converting to a list and sort tantony 6 3,212 Oct-07-2019, 03:30 PM
Last Post: perfringo
  Converting List into list of tuples ARV 4 4,746 Sep-28-2019, 04:58 AM
Last Post: perfringo
  Converting List to Libray prophet11 6 3,585 Apr-22-2019, 04:49 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020