将python字典转换为逗号分隔的键字符串和逗号分隔值字符串的优雅方法是什么?

时间:2022-02-09 21:05:52

I have a dictionary as follows:-

我有一本字典如下: -

dict={'a':'1','b':'2', 'c':'3'}

To convert it into into a comma separated keys string key_string and a comma separated values string val_string I do the following:-

要将其转换为逗号分隔的键字符串key_string和逗号分隔值字符串val_string,我执行以下操作: -

key_list=[]
val_list=[]

 for key,value in dict.iteritems():
     key_list.append(key)
     val_list.append(value)

 key_string = ','.join(key_list)
 val_string = ','.join(val_list)

The result is

结果是

 key_string = "a,b,c"
 val_string = "1,2,3" 

Is there a more efficient/elegant way to do this?

有没有更有效/更优雅的方式来做到这一点?

3 个解决方案

#1


Use str.join(iterable) (Hint: don't name your dict dict):

使用str.join(iterable)(提示:不要命名你的dict dict):

d = {'a':'1', 'b':'2', 'c':'3'}
print(",".join(d.keys()))
print(",".join(d.values()))

Output:

c,a,b
3,1,2

Note that a dictionary has no order. So the output does not have any order you can rely on, too.

请注意,字典没有订单。所以输出也没有你可以依赖的任何顺序。

#2


The obvious solution is to just use iterkeys and itervalues instead of iteritems:

显而易见的解决方案是使用iterkeys和itervalues而不是iteritems:

key_string = ','.join(d.iterkeys())
val_string = ','.join(d.itervalues())

If you're worried about the keys and values showing up in different orders, while Python allows dicts to iterate in any order they want, it does document here that if you iterate them over and over without doing anything else between you will get the same order:

如果你担心键和值会出现在不同的顺序中,而Python允许dicts按照他们想要的任何顺序进行迭代,那么它确实记录了如果你反复迭代它们而不做其他任何事情就会得到相同的结果订购:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

如果调用items(),keys(),values(),iteritems(),iterkeys()和itervalues()而没有对字典进行干预,则列表将直接对应。

(The 2.7 docs were never updated to say so, but it's also true for viewitems, viewkeys, and viewvalues.)

(2.7文档从未更新过,但对于viewitems,viewkeys和viewvalues也是如此。)


At least in CPython, it will probably be slightly more efficient to use keys and values instead of iterkeys and itervalues (because, when given an iterator, the CPython implementation of str.join just makes a list out of it), but I doubt that matters. As Padraic Cunningham points out in the comments, for the keys (but not the values), you may be able to get the same list even faster with just list(d) instead of d.keys() (although maybe not—it avoids a LOAD_ATTR call, but at the cost of a LOAD_NAME, unless you've first copied list to a local so it can be LOAD_FASTed).

至少在CPython中,使用键和值而不是iterkeys和itervalues可能会稍微高效一些(因为,当给定一个迭代器时,str.join的CPython实现只是从中创建一个列表),但我怀疑事项。正如Padraic Cunningham在评论中指出的那样,对于键(但不是值),你可以使用list(d)而不是d.keys()来更快地获得相同的列表(虽然可能不是 - 它避免了一个LOAD_ATTR调用,但代价是LOAD_NAME,除非您先将列表复制到本地,因此它可以是LOAD_FASTed)。


Finally, if you want to do it with iteritems (let's say you're using a broken not-quite-compliant Python interpreter that randomizes the iteration order each time), you can use zip for that:

最后,如果你想用iteritems(假设你使用的是一个破碎的不完全兼容的Python解释器,每次都使迭代顺序随机化),你可以使用zip:

keys, values = zip(*d.iteritems())

That turns a sequence of pairs into a pair of sequences.

这将一对序列转换为一对序列。

#3


You could do it like this:

你可以这样做:

key_string = ','.join(dict.keys()) 
val_string = ','.join(dict.values())

#1


Use str.join(iterable) (Hint: don't name your dict dict):

使用str.join(iterable)(提示:不要命名你的dict dict):

d = {'a':'1', 'b':'2', 'c':'3'}
print(",".join(d.keys()))
print(",".join(d.values()))

Output:

c,a,b
3,1,2

Note that a dictionary has no order. So the output does not have any order you can rely on, too.

请注意,字典没有订单。所以输出也没有你可以依赖的任何顺序。

#2


The obvious solution is to just use iterkeys and itervalues instead of iteritems:

显而易见的解决方案是使用iterkeys和itervalues而不是iteritems:

key_string = ','.join(d.iterkeys())
val_string = ','.join(d.itervalues())

If you're worried about the keys and values showing up in different orders, while Python allows dicts to iterate in any order they want, it does document here that if you iterate them over and over without doing anything else between you will get the same order:

如果你担心键和值会出现在不同的顺序中,而Python允许dicts按照他们想要的任何顺序进行迭代,那么它确实记录了如果你反复迭代它们而不做其他任何事情就会得到相同的结果订购:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

如果调用items(),keys(),values(),iteritems(),iterkeys()和itervalues()而没有对字典进行干预,则列表将直接对应。

(The 2.7 docs were never updated to say so, but it's also true for viewitems, viewkeys, and viewvalues.)

(2.7文档从未更新过,但对于viewitems,viewkeys和viewvalues也是如此。)


At least in CPython, it will probably be slightly more efficient to use keys and values instead of iterkeys and itervalues (because, when given an iterator, the CPython implementation of str.join just makes a list out of it), but I doubt that matters. As Padraic Cunningham points out in the comments, for the keys (but not the values), you may be able to get the same list even faster with just list(d) instead of d.keys() (although maybe not—it avoids a LOAD_ATTR call, but at the cost of a LOAD_NAME, unless you've first copied list to a local so it can be LOAD_FASTed).

至少在CPython中,使用键和值而不是iterkeys和itervalues可能会稍微高效一些(因为,当给定一个迭代器时,str.join的CPython实现只是从中创建一个列表),但我怀疑事项。正如Padraic Cunningham在评论中指出的那样,对于键(但不是值),你可以使用list(d)而不是d.keys()来更快地获得相同的列表(虽然可能不是 - 它避免了一个LOAD_ATTR调用,但代价是LOAD_NAME,除非您先将列表复制到本地,因此它可以是LOAD_FASTed)。


Finally, if you want to do it with iteritems (let's say you're using a broken not-quite-compliant Python interpreter that randomizes the iteration order each time), you can use zip for that:

最后,如果你想用iteritems(假设你使用的是一个破碎的不完全兼容的Python解释器,每次都使迭代顺序随机化),你可以使用zip:

keys, values = zip(*d.iteritems())

That turns a sequence of pairs into a pair of sequences.

这将一对序列转换为一对序列。

#3


You could do it like this:

你可以这样做:

key_string = ','.join(dict.keys()) 
val_string = ','.join(dict.values())