PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to combine a list with dictionaries and values outside to allow for loop

 July 21, 2022     append, dictionary, list, python, python-3.x     No comments   

Issue

It's hard for me to explain in the title, but I have a list of 2 dictionaries data, and I want to insert things and stuff into them according to index via for loop or other iterators.

this is what I have:

things = ['7121703099311426821', '7114869117433154821', ]
stuff = ['fjfueirjk', 'aoiwhef', ]
data = [{'data1': 1009, 'data2': 52, 'data3': 43, 'data4': 45000}, {'data1': 115, 'data2': 7, 'data3': 9, 'data4': 1814}]

And I want them to be like:

data = {'id1':7121703099311426821, 'stuff: 'fjfueirjk', 'data1': 1009, 'data2': 52, 'data3': 43, 'data4': 45000}, {'id1':7114869117433154821, 'stuff': 'aoiwhef', 'data1': 115, 'data2': 7, 'data3': 9, 'data4': 1814}

So that I can say

for x in data:
    print(x['id1'])
    print(x['stuff'])
    print(x['data1'])
# do stuff

Solution

One approach, IIUC:

res = [{ "id" : thing, "stuff" : s, **d} for thing, s, d in zip(things, stuff, data)]
print(res)

Output

[{'id': '7121703099311426821', 'stuff': 'fjfueirjk', 'data1': 1009, 'data2': 52, 'data3': 43, 'data4': 45000}, {'id': '7114869117433154821', 'stuff': 'aoiwhef', 'data1': 115, 'data2': 7, 'data3': 9, 'data4': 1814}]


Answered By - Dani Mesejo
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing