临时打包字典 [英] Temporarily unpack dictionary

查看:153
本文介绍了临时打包字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个这样的dic

  my_dictionary = {'a':1,'c' 'b':20,'d':7} 

现在,我想用我的dic:

  if my_dictionary ['a'] == 1和my_dictionary ['d'] == 7:
打印my_dictionary ['c']

这看起来很可笑,因为我输入my_dictionary 3次! p>

所以有什么语法可以让我做这样的事情:

  in my_dictionary:
如果一个== 1和d == 7:
打印c






如果在我的dic中没有什么更多的东西(在这种情况下是b),这实际上会起作用:

  def f(a,d,c):
如果一个== 1和d == 7:
print c

f(** my_dictionary)


解决方案

p>您可以将您的功能更改为

  def f(a,d,c,** args):
如果一个== 1和d == 7:
print c

然后即使您在dict中有其他项目,它也会工作。


Say, I have a dic like this

my_dictionary = {'a':1,'c':5,'b':20,'d':7}

Now, I want to do this with my dic:

if my_dictionary['a'] == 1 and my_dictionary['d'] == 7:
    print my_dictionary['c']

This looks ridiculous because I am typing my_dictionary 3 times!

So is there any syntax which would allow me to do something like this:

within my_dictionary:
    if a == 1 and d == 7:
        print c


This would actually work if I didn't have anything more (in this case b) in my dic:

def f(a,d,c):
    if a == 1 and d == 7:
        print c 

f(**my_dictionary)

解决方案

You can change your function to

def f(a,d,c,**args):
    if a == 1 and d == 7:
        print c

then it will work even if you have other items in the dict.

这篇关于临时打包字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆