简体   繁体   English

如何在defaultdict中转换/更新键值信息?

[英]How to convert/update the key-values information in defaultdict?

How do I convert the following defaultdict() ? 如何转换以下defaultdict()

defaultdict(<class 'dict'>, {
  'key1_A': {
    'id': 'key1',
    'length': '663', 
    'type': 'A'},
  'key1_B': {
    'id': 'key1',
    'length': '389',
    'type': 'B'},
  'key2_A': {
    'id': 'key2',
    'length': '865',
    'type': 'A'},
  'key2_B': {
    'id': 'key2',
    'length': '553',
    'type': 'B' ........}})
  • the value of the id ie key1 becomes the key, and the key called length is changed to length_A or B with corresponding values belonging in the earlier type . value of the id ie key1value of the id ie key1成为密钥,并且将key called lengthkey called length更改为length_A or B并且对应的值属于较早的type

    defaultdict(<class 'dict'>, { 'key1': { 'length_A': '663', 'length_B': '389'}, 'key2': { 'length_A': '865', 'length_B': '553'}})

Thanks, 谢谢,

I think this does what you want: 我认为这可以满足您的需求:

from collections import defaultdict
import pprint

d = {
    'key1_A': {
        'id': 'key1',
        'length': '663', 
        'type': 'A',
    },
    'key1_B': {
        'id': 'key1',
        'length': '389',
        'type': 'B',
    },
    'key2_A': {
        'id': 'key2',
        'length': '865',
        'type': 'A',
    },
    'key2_B': {
        'id': 'key2',
        'length': '553',
        'type': 'B',
    },
}

transformed = defaultdict(dict)
for v in d.values():
    transformed[v["id"]]["length_{}".format(v["type"])] = v["length"]

pprint.pprint(transformed)

# Output:
# defaultdict(<class 'dict'>,
#             {'key1': {'length_A': '663', 'length_B': '389'},
#              'key2': {'length_A': '865', 'length_B': '553'}})

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

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