What is the Pythonic way to write this loop?

for jr in json_reports:
  jr['time_created'] = str(jr['time_created'])


Asked by: Sawyer689 | Posted: 06-12-2021






Answer 1

Looks to me that you're already there

Answered by: Lucas722 | Posted: 07-01-2022



Answer 2

That would be the pythonic way to write the loop if you need to assign it to the same list.

If you just want to pull out strings of all time_created indices in each element of json_reports, you can use a list comprehension:

strings = [str(i['time_created']) for i in json_reports]

Answered by: William893 | Posted: 07-01-2022



Similar questions

python - More pythonic way to write this?

I have this code here: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'attr') # None Which works, but I am not particularly fond of this line: return None if not m e...


python - How to write more Pythonic Code

I started learning python today from the tutorial on the official site. When reading about filter(function, sequence) i thought of making a function that returns if a number is prime to use it with the filter. notDividedBy = [2,3,4,5,6,7,8,9] def prime(num): """True if num is prime, false otherwise""" copy = notDividedBy[:] check = True if num in copy: c...


python - pythonic way to write this code

I have this ugly piece of code.. orders = got_something_from_db() if orders: for order in orders: #print order event_id = order["event_id"] if event_id in event_id_dict: # something i grabbed earlier product_id = order["product_id"] # products in an event qty = order["qty"] if product_id in product_sku_dict: sku_id =product_s...


python - Pythonic way to write a loop

I have two lists: a = [1, 2, 3] and b = [4, 5, 6]. I have used two loops in python to subtract each element of b from each element of a. import numpy as np a = [1, 2, 3] b = [4, 5, 6] p = -1 result = np.zeros(len(a)*len(a)) for i in range(0,len(a)): for j in range(0,len(a)): p = p + 1 result[p] = a[i] - b[j] My...


python - Is there a more pythonic way to write this?

I'm looking to make this a little more pythonic. user_df[-1:]['status_id'].values[0] in {3,5} I ititially tried user_id.ix[-1:, 'status_id'].isin([3,5]), but didn't work. Any suggestions? The top version works, but looks a little weird.


python - How to write for loops in a "pythonic" way

I would like to know if there is a "python-ic" way to write the following nested forloops with if statements: nonelist = [] for i in testlist: for e in i: if e == None: nonelist.append(i)


python - How do i write this code more pythonic way

I am writing Django's views to check if a valid album id is provided or not. But it looks cumbersome and hard to read. I want to make it more readable and short. I cant directly check data['id']. It will give error if its blank. def post(self, request): if len(request.body) > 0: data = json.loads(request.body.decode('utf-8')) else: return Response({'message': 'Album i...


python - Pythonic ways to use 'else' in a for loop

This question already has answers here:


python - How do you make this code more pythonic?

Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab & I'm using scipy ...


python - Pythonic way to return list of every nth item in a larger list

Say we have a list of numbers from 0 to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item, i.e. [0, 10, 20, 30, ... ]? Yes, I can do this using a for loop, but I'm wondering if there is a neater way to do this, perhaps even in one line?


python - Can this be made more pythonic?

I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability. Thanks from math import sqrt def isprime(n): if n ==2: return True if n % 2 ==0 : # evens return False max = in...


python - What is the pythonic way to unpack tuples?

This question already has answers here:


python - Pythonic way to check if a file exists?

This question already has answers here:


python - Pythonic way to create a numpy array from a list of numpy arrays

I generate a list of one dimensional numpy arrays in a loop and later convert this list to a 2d numpy array. I would've preallocated a 2d numpy array if i knew the number of items ahead of time, but I don't, therefore I put everything in a list. The mock up is below: >>> list_of_arrays = map(lambda x: x*ones(2), range(5)) >>> list_of_arrays [array([ 0., 0.]), array([ 1., 1.]), ar...


python - What is the most pythonic way to check if an object is a number?

Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector. Checking if something is int, float, ...


python - More pythonic way to write this?

I have this code here: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'attr') # None Which works, but I am not particularly fond of this line: return None if not m e...


python - Taking list's tail in a Pythonic way?

from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this piece of code gets executed many times in, say, update() method, and therefore it has to be quick as possible. Using ...


python - Is it pythonic for a function to return multiple values?

In python, you can have a function return multiple values. Here's a contrived example: def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also"). W...


python - A pythonic way to insert a space before capital letters

I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?


python - Is there a more Pythonic way to merge two HTML header rows with colspans?

I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to d...


python - What is the pythonic way to share common files in multiple projects?

Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to create a single package for them. Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. What is th...


python - Pythonic ways to use 'else' in a for loop

This question already has answers here:


python - pythonic way to compare compound classes?

I have a class that acts as an item in a tree: class CItem( list ): pass I have two trees, each with CItem as root, each tree item has some dict members (like item._test = 1). Now i need to compare this trees. I can suggest to overload a comparison operator for CItem: class CItem( list ): def __eq__( self, other ): # first compare items as lists if not list.__eq...


python - Pythonic URL Parsing

There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/secon...


list - Pythonic way to get some rows of a matrix

I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp Now that I've learnt a little bit more since then, I'd use a list comprehension like this:


python - How do you make this code more pythonic?

Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab & I'm using scipy ...


python - Pythonic Swap of 2 lists elements

I found that I have to perform a swap in python and I write something like this: arr[first], arr[second] = arr[second], arr[first] I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegant? EDIT: I think another example will show my doubts: self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[som...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top