In Python, I currently have a dictionary (it has a composite key from a list within a list) that looks similar to the following when I print it:
the first value is a number, the second value (A or B) refers to a text value and the numbers are a count of the times they appear in the original list of list that this dictionary was derived from.
What I need is a way of printing out the data in the following format. For the unique occurrences of the numeric value in the dictionary (ie. in this case the first and third values), print out the associated text value along with its count. So it would look like
Type: 111 Text Count
A 4
B 10
Total: 14
Type: 112 Text Count
A 3
Total: 3
I know I need to use some sort of while loop when combined with If statements. From what I have researched so far (pertinent to what I have been taught so far for Python), I need to write loops with if statements to print only what I want to print. So I need to print new Numeric Values the first time they occur, but not the second (or third or fourth, etc) time they occur. I assume to partially do this I put them in a variable, then compare them to the current value. If they are the same, I don’t print them, but if they are different, I print the “total” of the old numeric values, add it to the overall total, then print the new one.
Since this is homework, I will give you code that is almost the answer:
Outputs:
This requires very small modifications to get you to where you need to be.
EDIT: “explain how the
for k in [k for k in myDict if k.split(',')[0]==prefix]:works”There are two parts to that statement. The first is a simple for-loop (
for k in …), which works as usual. The second is the list comprehension[k for k in myDict if k.split(',')[0]==prefix]. This list comprehension can be rewritten as:and then you would do
There is something to be said about
for k in myDict. When you iterate over adictlike that, you iterate only over the keys. This is the same as sayingfor k in myDict.keys(). The difference is thatmyDict.keys()returns a new list (of the keys inmyDict) which you then iterate over, whereasfor k in myDictiterates directly over all the keys inmyDict