python字典和列表:如何转换它?

时间:2014-05-16 13:05:57

标签: python list dictionary

我有这种类型的词典:

dic = {
'blahAA,
AA': [
    u'cat'
],
'blahBB,
BB': [
    u'dog',
    u'bird'
],
'blahCC,
CC': [
    u'fish',
    u'horse',
    u'elephant'
]

}

blahXX是互联网链接,XX是id。 如何将其转换为具有如下列表:

list = [['cat AA'], ['dog bird BB'], ['fish horse elephant CC']] 

Optionnal: 理想情况下,我想在Gtk界面(组合框)中显示每个元素(猫,狗鸟等),而不显示XX,想要在选择中找到对应的互联网地址:

示例:

cat --Gtk--> blahAA
dog bird --Gtk--> blahBB
fish horse elephant --Gtk--> blahCC

有可能吗? 感谢

我显示结果的实际代码是:

choice = self.liste.get_active_text()   # choice from the user
for url in self.links:
    if id in url: 
         adress = url
self.champ.set_text(adress)             # adress display

3 个答案:

答案 0 :(得分:3)

[' '.join(map(str, x[1] + x[0].split(',')[1:])) for x in dic.items()]

Out[115]: ['cat AA', 'fish horse elephant CC', 'dog bird BB']

(map(str,seq)的优点是,如果列表中的某些元素是TypeError,它不会抛出int异常 - 你不能在Python中连接整数和字符串它是强类型语言,如果仍然是动态类型语言)

答案 1 :(得分:1)

>>> [v + [k.rsplit(',')[-1]] for k, v in dic.items()]
[['dog', 'bird', 'BB'], ['cat', 'AA'], ['fish', 'horse', 'elephant', 'CC']]

我真的不明白你想要连接每个子列表中的所有值的目的,但是你可以使用join的{​​{1}}方法来实现它:

str

更新:如果您要从这些网址中删除>>> [' '.join(v + [k.rsplit(',')[-1]]) for k, v in dict.items()] ['dog bird BB', 'cat AA', 'fish horse elephant CC'] 部分,请执行以下操作

.html

>>> [' '.join(v + [k[:-5].rsplit(',')[-1]]) for k, v in dict.items()] 返回一个没有最后5个字符的新字符串(在我们的例子中是k[:-5])。

答案 2 :(得分:0)

list = [[" ".join(v + [k.rsplit(',')[-1]])] for k,v in dic.items()]
print list