Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary Print First occurence

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.

like image 222
DarkGod Avatar asked Mar 18 '26 13:03

DarkGod


2 Answers

Instead of one flat dictionary, I would use a hierarchy of objects, such as dicts inside a dict, tuples inside a dict, etc.

Considering an example with dicts inside a dict:

data = { 
    '111': {
        'A': 4,
        'B': 10,
    },
    '112': {
        'A': 3
    },
}

Now you can more easily access the contents. For instance display properties inside '111':

for key in data['111']:
    print "%s\t%s" % (key, data['111'][key])

The desired output can be created somewhat trivially by combining two for-loops:

for datatype in data:
    print("Type: %s Text Count" % datatype)
    items = data[datatype]
    total = 0
    for key in items:
        print "%s\t%s" % (key, items[key])
        total += items[key]
    print("Total:\t%s\n" % total)

Running the above with the given data would result in the following output:

Type: 111 Text Count
A       4
B       10
Total:  14

Type: 112 Text Count
A       3
Total:  3
like image 143
jsalonen Avatar answered Mar 21 '26 02:03

jsalonen


Since this is homework, I will give you code that is almost the answer:

myDict = {'111, A': 4, '112, A': 3, '111, B': 10} # input

# keep track of the first half of the composite keys that you've already handled
# This is used to avoid redundant printing
done = set()

for key in myDict:
    # first half of your composite key (eg. '111')
    # I'll be using '111' to explain the rest of the code
    prefix = key.split(',')[0]

    if prefix not in done: # if you haven't already printed out the stuff for '111'
        print prefix # print '111'
        done.add(prefix) # add '111' to done, so that you don't print it out again

        # for all keys in myDict that are of the form "111,X" where X can be anything (e.g. A)
        for k in [k for k in myDict if k.split(',')[0]==prefix]:

            # print a <tab> and the suffix (in our example, "A") and the count value (in myDict, this value is 4)
            print '\t', k.split(',')[1], myDict[k]

Outputs:

111
     B 10
     A 4
112
     A 3

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:

myList = []
for k in myDict:
    if k.split(',')[0]==prefix:
        myList.append(k)

and then you would do

for k in myList:

There is something to be said about for k in myDict. When you iterate over a dict like that, you iterate only over the keys. This is the same as saying for k in myDict.keys(). The difference is that myDict.keys() returns a new list (of the keys in myDict) which you then iterate over, whereas for k in myDict iterates directly over all the keys in myDict

like image 28
inspectorG4dget Avatar answered Mar 21 '26 04:03

inspectorG4dget



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!