-1

I have a data structure called Deny:

{'1': {'From': '00:00:00:00:00:02', 'To': '00:00:00:00:00:01'},
 '2': {'From': '00:00:00:00:00:03', 'To': '00:00:00:00:00:04'}}

I need to loop through to print values associated with From and To. Here's what I have so far:

Calling the function:

self.Add(*Deny)

Called function:

def Add(*Deny):
    for x in Deny.values():
        log.debug("From is %s",x['From'])
        log.debug("To is %s",x['To'])

I get error message like: 'tuple' object has no attribute 'values'. I'm expecting an output like this:

From is 00:00:00:00:00:02
To is 00:00:00:00:00:01
From is 00:00:00:00:00:03
To is 00:00:00:00:00:04

Can anyone suggest a solution for this for loop?

Explore_SDN
  • 217
  • 1
  • 3
  • 10
  • 1
    I suggest you read the documentation and stop trying to write C in Python. `*` is not a pointer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists – TessellatingHeckler Aug 25 '15 at 17:46
  • All you have to do is get rid of that `*` and your code will work as intended... – atlspin Aug 25 '15 at 17:51
  • And just for kicks, here is a one-liner for you: ``log.debug('\n'.join('From is {}\nTo is {}'.format(x['From'], x['To']) for x in Deny.values()))``. I didn't test it, but I'd think it performs a bit better than your code. – pzp Aug 25 '15 at 17:57
  • If i get rid off * in my code, i get this message "Add() takes exactly 1 argument (2 given)" . What should i do more? @atlspin – Explore_SDN Aug 25 '15 at 18:13
  • Do you have add() as part of a class? If so then it is getting 'self' as its first parameter, and you need to account for that in the signature – atlspin Aug 25 '15 at 18:21

2 Answers2

4

You are using *args which is a tuple of arguments so calling .values on a tuple is obviously not going to work, it would be **kwargs if you want to use keyword args which returns a dict so .values() would work, if you want to iterate over the args just iterate over Deny:

for x in Deny:

If you are just passing a single argument ie your dict then forget * and ** just use def Add(Deny) and then you can use for x in Deny.values():

what-does-double-star-and-star-do-for-python-parameter

Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

When you use *Deny in a method definition, * refers to a tuple of arguments, i.e. later if use the Add method with arguments Add(a,b,c,d), variable Deny inside the method will be a tuple (a,b,c,d). For your problem, a simple modification as following would work.

def Add(Deny):
    for x in Deny.values():
        print("From is %s"%x['From'])
        print("To is %s"%x['To'])
kampta
  • 4,748
  • 5
  • 31
  • 51