Asked  7 Months ago    Answers:  5   Viewed   23 times
for k, v in d.iteritems():
    if type(v) is dict:
        for t, c in v.iteritems():
            print "{0} : {1}".format(t, c)

I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key value pairs...etc. Any help?

EDIT

How about this? It still only prints one thing.

def printDict(d):
    for k, v in d.iteritems():
        if type(v) is dict:
            printDict(v)
        else:
            print "{0} : {1}".format(k, v)

Full Test Case

Dictionary:

{u'xml': {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'},
      u'port': u'11'}}

Result:

xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}

 Answers

26

As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.

Something like :

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))
Tuesday, June 1, 2021
 
kat_indo
answered 7 Months ago
30
for(int i=0;i<ROW_COUNT;i++){
    for(j=0;j<COLUMN_COUNT;j++){
        int editTextId=getResId("box"+i+j,this,id.class);
        int textViewId=getResId("answerbox"+i+j,this,id.class);

        EditText et=(EditText)findViewById(editTextId);
        TextView tv=(TextView)findViewById(textViewId);

       //Then do your comparison as you like and do the rest. 
    }   
}

public static int getResId(String variableName, Context context, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}
Thursday, September 2, 2021
 
ssarabando
answered 3 Months ago
93

First problem recursion - a recursive function is one that calls itself! A simple example of this is a countdown function such as:

def countdown(n):
    # counting down the recursive way! 
    if n > 0:
        print n
        countdown(n-1)
    else:
        return

Calling countdown(10) will print 10, 9, 8,.., 2, 1.

You can see that countdown is passed a number n and all it does is prints that number and then calls itself but passing n-1 this time. Only once n=0 is passed will it not have anything left to do so each recursive call is returned. For your dictionary of dictionaries case (lets call it a library of dictionaries to avoid confusion) a recursive printing approach would be:

  1. Pass the whole library to the printing routine.
  2. Print the first dictionary.
  3. Recursively call itself and pass the library minus the first dictionary.
  4. Return when the library has no more dictionaries to print.

Something like this:

def recursive_print(dic):

    if len(dic) > 0:                  # If dictionaries in library > 0 
        print dic.keys()[0]           # Print the key i.e Earth
        print dic[dic.keys()[0]]      # Print the dictionary value for i.e Earth
        dic.popitem()                 # Remove the Earth dictionary from library
        recursive_print(dic)          # Recursive call 
    else:
        return                        # Printed all, return up the stack.


planets = data(file)
recursive_print(planets)

The next step would be instead of printing the dictionaries in there current format you would do some calculations/conversion so the output is valid quickdraw input, like the code you have already for printing circles using quickdraw.

You will need to worry about the scale, to ensure all objects fit on the drawing surface find the celestial body with the largest Orbital Radius and use that to calculate the scale.

Using list comprehension similar to your code we can find the largest value:

max([planet[key]['Orbital Radius'] for key in planet])

>>> 8595000

scale = gridsize/max([planet[key]['Orbital Radius'] for key in planet])
Thursday, September 23, 2021
 
RANGER
answered 3 Months ago
98

We scan every element in the sequence, and proceeds into deeper recursion if the current item is a sub-sequence, or yields it's mapping if we reached a non-sequence data type (could be int, str, or any complex classes).

We use collections.Sequence to generalize the idea for every sequence, and not only tuples or lists, and type(item) upon yield to ensure that the sub-sequences we get back remains of the same type they were.

from collections import Sequence

def recursive_map (seq, func):
    for item in seq:
        if isinstance(item, Sequence):
            yield type(item)(recursive_map(item, func))
        else:
            yield func(item)

Demo:

>>> numbers = (1, 2, (3, (4, 5)), 7)
>>> mapped = recursive_map(numbers, str)
>>> tuple(mapped)
('1', '2', ('3', ('4', '5')), '7')

Or a more complex example:

>>> complex_list = (1, 2, [3, (complex('4+2j'), 5)], map(str, (range(7, 10))))
>>> tuple(recursive_map(complex_list, lambda x: x.__class__.__name__))
('int', 'int', ['int', ('complex', 'int')], 'map')
Sunday, September 26, 2021
 
Eddas
answered 2 Months ago
44

In modern browsers Object.getOwnPropertyNames() and Object.getPrototypeOf() will help you get all properties of all objects in the prototype chain.

http://jsfiddle.net/FtVXN/

var obj = window;

do Object.getOwnPropertyNames(obj).forEach(function(name) {
       console.log(name);
   });
while(obj = Object.getPrototypeOf(obj));

If you want to see the separation of the prototype objects, then add a line that provides a divider.

http://jsfiddle.net/FtVXN/1/

var obj = window;

do {
    Object.getOwnPropertyNames(obj).forEach(function(name) {
        console.log(name);
    });
    console.log("=============================");
} while(obj = Object.getPrototypeOf(obj));

I do think I recall that in Firefox, some globals don't appear until you access them. You may need to do a little experimenting if you find that to be the case.

Thursday, November 4, 2021
 
napolux
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share