简体   繁体   English

如何在Python dict的值前附加键?

[英]How to append a key before a value in Python dict?

I have a dict 我有一个dict

x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'}

Now I want to append the key before values, so my expected output is: 现在,我想将键附加在值之前,所以我的预期输出是:

{'[a]': '[a](1234)', '[b]': '[b](2345)', '[c]': '[c](xyzad)'}

I can do it using for loop like below: 我可以使用如下的for循环来做到这一点:

for k,v in x.items():
    x.update({k:k+v})

I am looking for efficent way of doing this or I should stick to my current approach? 我正在寻找有效的方法,还是应该坚持目前的方法?

Your approach seems fine. 您的方法似乎很好。 You could also use a dictionary comprehension, for a more concise solution: 您还可以使用字典理解,以获得更简洁的解决方案:

x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'}

{k: k+v for k,v in x.items()}
# {'[a]': '[a](1234)', '[b]': '[b](2345)', '[c]': '[c](xyzad)'}

Another way: 其他方式:

x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'}
dict(((key, key + x[key]) for key in x))
>>>{'[a]': '[a](1234)', '[b]': '[b](2345)', '[c]': '[c](xyzad)'}

For smaller size dictionaries, the dictionary comprehension solution by @yatu is the best. 对于较小型的字典, @yatudictionary comprehension解决方案是最好的。

Since you mentioned that the data set is large & you would like to avoid for loop, pandas would be the recommended solution. 由于您提到数据集很大,并且您希望避免for循环,因此pandas是推荐的解决方案。

  1. Create pandas dataframe from dict 'x' 从字典'x'创建熊猫数据框
  2. Transform the dataframe & write to a new dictionary 转换数据框并写入新字典

Code: 码:

# Read dictionary to a dataframe
df = pd.DataFrame(list(x.items()), columns=['Key', 'Value'])

Out[317]: 
   Key    Value
0  [a]   (1234)
1  [b]   (2345)
2  [c]  (xyzad)

# Since the transformation is just concatenating both key and value, this can be done while writing to the new dictionary in a single step.
y = dict(zip(df.Key, df.Key+df.Value))

Out[324]: {'[a]': '[a](1234)', '[b]': '[b](2345)', '[c]': '[c](xyzad)'}

This would be much faster for large data sets but I'm not sure how to compare the timings. 对于大型数据集,这会更快,但我不确定如何比较时序。

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

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