简体   繁体   English

在Python中混合列表和字典

[英]Mixing List and Dict in Python

I was wondering how do you mix list and dict together on Python? 我想知道如何在Python上将列表和字典混合在一起? I know on PHP, I can do something like this: 我知道在PHP上,我可以这样做:

$options = array(
    "option1", 
    "option2", 
    "option3" => array("meta1", "meta2", "meta3"), 
    "option4" 
);

The problem is python have different bracket for different list. 问题是python对于不同的列表有不同的括号。 () for tuple, [] for list, and {} for dict. ()表示元组,[]表示列表,{}表示字典。 There don't seems to be any way to mix them and I'm keep getting syntax errors. 似乎没有任何办法将它们混合在一起,而且我一直在获取语法错误。

I am using python 2.7 now. 我现在正在使用python 2.7。 Please advice how to do it correctly. 请建议如何正确执行。

Much thanks, 非常感谢,

Rufas Rufas

Update 1: 更新1:

I'll slightly elaborate what I'm trying to do. 我会稍微详细说明我要做什么。 I am trying to write a simple python script to do some API requests here: 我正在尝试编写一个简单的python脚本来执行一些API请求:

http://www.diffbot.com/products/automatic/article/ http://www.diffbot.com/products/automatic/article/

The relevant part is the fields query parameters. 相关部分是字段查询参数。 It is something like ...&fields=meta,querystring,images(url,caption)... . 它类似于...&fields = meta,querystring,images(url,caption)...。 So the above array can be written as (in PHP) 所以上面的数组可以写成(在PHP中)

$fields = array(
    'meta',
    'querystring',
    'images' => array('url', 'caption')
);

And the $fields will be passed to a method for processing. $ fields将被传递给方法进行处理。 The result will be returned, like this: 结果将返回,如下所示:

$json = diffbot->get("article", $url, $fields);

The thing is - I have no problem in writing it in PHP, but when I try to write it in Python, the thing is not as easy as it seems... 事情是-用PHP编写它没有问题,但是当我尝试用Python编写它时,事情并不像看起来那么容易...

You can do it this way: 您可以这样操作:

options = {
    "option1": None, 
    "option2": None,
    "option3": ["meta1", "meta2", "meta3"], 
    "option4": None,
}

But options is a dictionary in this case. 但是在这种情况下, options是字典。 If you need the order in the dictionary you can use OrderedDict. 如果您需要字典中的订单,则可以使用OrderedDict。

How can you use OrderedDict ? 如何使用OrderedDict

from collections import OrderedDict

options = OrderedDict([
    ("option1", None),
    ("option2", None),
    ("option3", ["meta1", "meta2", "meta3"]), 
    ("option4", None),
])

print options["option3"]
print options.items()[2][1]
print options.items()[3][1]

Output: 输出:

['meta1', 'meta2', 'meta3']
['meta1', 'meta2', 'meta3']
None

Here you can access options either using keys (like option3 ), or indexes (like 2 and 3 ). 在这里,您可以使用键(如option3 )或索引(如23 )访问options

Disclaimer. 免责声明。 I must stress that this solution is not one-to-one mapping between PHP and Python. 我必须强调,这种解决方案不是PHP和Python之间的一对一映射。 PHP is another language, with other data structures/other semantics etc. You can't do one to one mapping between data structures of Python and PHP. PHP是另一种语言,具有其他数据结构/其他语义等。您无法在Python和PHP的数据结构之间进行一对一映射。 Please also consider the answer of Hyperboreus (I gave +1 to him). 还请考虑Hyperboreus的答案(我给了他+1)。 It show another way to mix lists and dictionaries in Python. 它显示了在Python中混合列表和字典的另一种方法。 Please also read our discussion below. 还请阅读下面的讨论。

Update1. UPDATE1。

How can you process such structures? 您如何处理这样的结构?

You must check which type a value in each case has. 您必须检查每种情况下值的类型。 If it is a list ( type(v) == type([]) ) you can join it; 如果它是一个列表( type(v) == type([]) ),则可以加入它; otherwise you can use it as it is. 否则,您可以按原样使用它。

Here I convert the structure to a URL-like string: 在这里,我将结构转换为类似URL的字符串:

options = {
    "option1": None,
    "option2": None,
    "option3": ["meta1", "meta2", "meta3"], 
    "option4": "str1",
}

res = []
for (k,v) in options.items():
    if v is None:
        continue
    if type(v) == type([]):
        res.append("%s=%s" % (k,"+".join(v)))
    else:
        res.append("%s=%s" % (k,v))

print "&".join(res)

Output: 输出:

option4=str1&option3=meta1+meta2+meta3

This seems to do the same thing: 这似乎做同样的事情:

options = {0: 'option1',
    1: 'option2',
    2: 'option4'
    'option3': ['meta1', 'meta2', 'meta3'] }

More in general: 一般而言:

[] denote lists, ie ordered collections: [1, 2, 3] or [x ** 2 for x in [1, 2, 3]] []表示列表,即有序集合: [1, 2, 3][x ** 2 for x in [1, 2, 3]]

{} denote sets, ie unordered collections of unique (hashable) elements, and dictionaries, ie mappings between unique (hashable) keys and values: {1, 2, 3} , {'a': 1, 'b': 2} , {x: x ** 2 for x in [1, 2, 3]} {}表示集合,即唯一(可哈希)元素的无序集合,以及字典,即唯一(可哈希)键与值之间的映射: {1, 2, 3}{'a': 1, 'b': 2}{x: x ** 2 for x in [1, 2, 3]}

() denote (among other things) tuples, ie immutable ordered collections: (1, 2, 3) ()表示(除其他外)元组,即不可变的有序集合: (1, 2, 3)

() also denote generators: (x ** 2 for x in (1, 2, 3)) ()还表示生成器: (x ** 2 for x in (1, 2, 3))表示(x ** 2 for x in (1, 2, 3))

You can mix them any way you like (as long as elements of a set and keys of a dictionary are hashable): 您可以按自己喜欢的方式混合它们(只要集合的元素和字典的键是可哈希的):

>>> a = {(1,2): [2,2], 2: {1: 2}}
>>> a
{(1, 2): [2, 2], 2: {1: 2}}
>>> a[1,2]
[2, 2]
>>> a[1,2][0]
2
>>> a[2]
{1: 2}
>>> a[2][1]
2

I'm pretty sure there are 3 answers for my question and while it received a -1 vote, it is the closest to what I want. 我很确定我的问题有3个答案,虽然它获得了-1票,但它与我想要的最接近。 It is very strange now that it is gone when I want to pick that one up as "accepted answer" :( 现在很奇怪,当我想拿起一个作为“可接受的答案”时,它消失了:(

To recap, the removed answer suggest I should do this: 概括地说,删除的答案建议我应该这样做:

options = [
    "option1", 
    "option2", 
    {"option3":["meta1", "meta2", "meta3"]}, 
    "option4" 
]

And that fits nicely how I want to process each item on the list. 这正好适合我要如何处理列表中的每个项目。 I just loop through all values and check for its type. 我只是遍历所有值并检查其类型。 If it is a string, process it like normal. 如果是字符串,请像平常一样处理它。 But when it is a dict/list, it will be handled differently. 但是,当它是字典/列表时,将以不同的方式处理。

Ultimately, I managed to make it work and I get what I want. 最终,我设法使它起作用,并且得到了想要的东西。

Special thanks to Igor Chubin and Hyperboreus for providing suggestions and ideas for me to test and discover the answer I've been looking for. 特别感谢Igor Chubin和Hyperboreus为我提供的建议和想法,以测试和发现我一直在寻找的答案。 Greatly appreciated. 不胜感激。

Thank you! 谢谢!

Rufas Rufas

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM