简体   繁体   中英

How to iterate list items to store as a dictionary and write it to json?

I have a list and I want to iterate and write it to write to json. For example:

lis_1 = ['fellow','hello','yellow']

Now I store it as a dictionary:

items_main = {}
new_list = []
result_2 = {}
items = {}
lis_1 = ['fellow','hello','yellow']
for i,l in enumerate(lis_1):
    key, value = str(i+1), str(lis_1[i])
    items[key] = value
    new_list.append(items)

for d in new_list:
    result_2.update(d)
print(result_2)

I am also few other variable to the same

name = 'buddy'
year = 2008

sample = {    
    "FDRID1":{
         "1": {
            "Property_name":{ 
              "1": str(name )
               },

             items_main['Building Highlights'] = result_2

              "Year":{
                  "1":str(year)
                     }
                }
             }
        }

with open(out_file, 'w') as fp:
    json.dump(sample, fp)

Expected output:

"FDRID1":{
          "1": {
         "Property_name":{ 
              "1": "buddy"
               },

          "BuildingHighlights":{
               "1":"fellow",
               "2":"hello",
               "3":"yellow"
                  },
        "Year":{
             "1":'2008'
                }
       }
  }

Also if the **lis_1 = ['']**ie, (empty).The output must be:

"FDRID1":{
              "1": {
             "Property_name":{ 
                  "1": "buddy"
                   },

              "BuildingHighlights":{
                   "1":"",
                   "
                      },
            "Year":{
                 "1":'2008'
                    }
           }
      }

I'm not quite sure I've understood exactly what you are trying to do:

result_1 = {str(i): v for i, v in enumerate(lis_1, 1)} if lis_1 else {'1', ''}

Your example output for the empty list isn't valid json because it has a spurious " - assuming this is just an editing error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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