I did some research on how to use named array from PHP in python, while i found the following code example as they said can be done with dictionary.
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
Source: Portion of code getting from here
Reference: Python references
But how could i adding a new value through a loop? While the references shown on how to adding single value by simply shows['key']="value" but i can't linking both of them. Can anyone please show me how to add the value into this dictionary through a loop?
For example:
for message in messages:
myvariable inside having two field
- Message
- Phone number
Update
May i know how could i loop them out to display after aped list into dictionary? Thanks!
You should be adding the dictionary into an array like :
friends = []
for message in messages:
dict = {"message" : message.message, "phone" : message.phone }
friends.append(dict)
to loop again, you can do it this way :
for friend in friends:
print "%s - %s" % (friend["message"], friend["phone"])
Effectively your example is a list of dictionaries, in PHP terms array of associative arrays.
To add an item you can do:
shows.append({ "id" : 3, "name" : "House M.D."})
[] denotes a list, or an array.
{} denotes a dictionary or an associative array.
In short, you can do (list comprehension)
message_informations = [{"message": m.message, "phone": m.phone} for m in messages]
If you want to assing an id for each message_information and store in a dictionary (dict comprehension)
{_id: {"message": m.message, "phone": m.phone} for _id, m in enumerate(messages)}
Related
I am getting data from an API and storing it in json format. The data I pull is in a list of dictionaries. I am using Python. My task is to only grab the information from the dictionary that matches the ticker symbol.
This is the short version of my data printing using json dumps
[
{
"ticker": "BYDDF.US",
"name": "BYD Co Ltd-H",
"price": 25.635,
"change_1d_prc": 9.927101200686117
},
{
"ticker": "BYDDY.US",
"name": "BYD Co Ltd ADR",
"price": 51.22,
"change_1d_prc": 9.843448423761526
},
{
"ticker": "TSLA.US",
"name": "Tesla Inc",
"price": 194.7,
"change_1d_prc": 7.67018746889343
}
]
Task only gets the dictionary for ticker = TSLA.US. If possible, only get the price associated with this ticker.
I am unaware of how to reference "ticker" or loop through all of them to get the one I need.
I tried the following, but it says that its a string, so it doesn't work:
if "ticker" == "TESLA.US":
print(i)
Try (mylist is your list of dictionaries)
for entry in mylist:
print(entry['ticker'])
Then try this to get what you want:
for entry in mylist:
if entry['ticker'] == 'TSLA.US':
print(entry)
This is a solution that I've seen divide the python community. Some say that it's a feature and "very pythonic"; others say that it's a bad design choice we're stuck with now, and bad practice. I'm personally not a fan, but it is a way to solve this problem, so do with it what you will. :)
Python function loops aren't a new scope; the loop variable persists even after the loop. So, either of these are a solution. Assuming that your list of dictionaries is stored as json_dict:
for target_dict in json_dict:
if target_dict["ticker"] == "TESLA.US":
break
At this point, target_dict will be the dictionary you want.
It is possible to iterate through a list of dictionaries using a for loop.
for stock in list:
if stock["ticker"] == "TSLA.US":
return stock["price"]
This essentially loops through every item in the list, and for each item (which is a dictionary) looks for the key "ticker" and checks if its value is equal to "TSLA.US". If it is, then it returns the value associated with the "price" key.
I am trying to use map() on a list of dictionaries to get a name and id only.
My input:
employees = [
{"id": 12113, "name": "Jim", "department": "Sales"},
{"id": 12342, "name": "Michael", "department": "Management"},
{"id": 23312, "name": "Dwight", "department": "Sales"},
]
What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.
My function currently contains what is below but isn't returning values, only: <map object at 0x7f3b0bb6d460>, <map object at 0x7f78e7242670>.
My code:
def name_id(employees):
name_and_ids = [{map(('name', 'id'), emp) for emp in employees}]
print(list(name_id)) ### to see if what I want is being output or not
return name_and_ids
I am calling my function with:
print(f"Name and ids: {name_id(employees)}")
I am fairly new to python and am getting confused with comprehensions in general, whether list or dictionary comprehensions. I did see you can use dict and/or zip but would like to learn something new with map().
Any advice/help to push me in the right direction of getting what I want would be much appreciated.
What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.
You need a dictionary comprehension:
result = {
emp['name']: emp['id']
for emp in employees
}
map is not an appropriate tool for the job, because it converts N things to N other things, whereas you need to convert N things (3 employees) into one thing (a dict). If you insist, you could use map to convert the source list into a list of key-value tuples and then apply dict to the result:
from operator import itemgetter
result = dict(
map(itemgetter('name', 'id'), employees)
)
This style is not considered "pythonic" though.
The map function doesn't do anything related to what you want here. It's leading you astray.
Instead, just do the mapping you want yourself in the dict comprehension you already have:
name_and_ids = {emp['name']: emp['id'] for emp in employees}
I have a list of dictionaries generated by:
r=requests.get(url, headers={key:password})
import_data_list.append(r.json())
I want to delete the first key from these dictionaries. I know I can delete the dictionaries in the list with:
del import_data_list[0]
But how do I delete a key from the dictionary in the list, rather than deleting the whole dictionary.
I tried something like:
del import_data_list[0["KEY"]]
Obviously it doesnt work!
Any help would be much appreciated and sorry if its a dumb question. Still learning!
If you want to delete the first key (you don't know its name, you just know it is the first one) from these dictionaries, I suggest you to loop over the dictionaries of the list. You can use list(d.keys())[0] or even list(d)[0] to get the first key of a dictionary called d.
Here is an example:
for d in import_data_list:
k = list(d)[0] # get the first key
del d[k] # delete it from the dictionary
print(import_data_list)
You can also do it with one-lined style using a list comprehension, which I find quite smart too. In this case you also retrieve the values of the first keys in a list, which might be useful:
r = [d.pop(list(d)[0]) for d in import_data_list]
print(import_data_list)
Note that it works only with python version >= 3.6 (but not with version <= 3.5 because dictionaries are not ordered)
Assume you have this list of dictionaries.
myList = [
{
"Sub1List1" : "value",
"Sub2List1" : "value",
"Sub3List1" : "value",
"Sub4List1" : "value"
},
{
"Sub1List2" : "value",
"Sub2List2" : "value",
"Sub3List2" : "value",
"Sub4List2" : "value"
},
{
"Sub1List3" : "value",
"Sub2List3" : "value",
"Sub3List3" : "value",
"Sub4List3" : "value"
}
]
Now, if you want to delete key Sub1List1 from the first list, you can do this by using :
del myList[0]["Sub1List1"]
Use the command:
del dictionaryName[KEY]
I have a JSON file, and what I am trying to do is getting this specific field '_id'. Problem is that when I use json.load('input_file'), it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
because I keep getting this error: TypeError: list indices must be integers or slices, not str
What I also tried to do is:
data = json.load(input_file)[0]
It kinda works. Now, my type is a dictionary, and I can access like this: data['_id']
But I only get the first '_id' from the archive...
So, what I would like to do is add all '_id' 's values into a list, to use later.
input_file = open('input_file.txt')
data = json.load(input_file)[0]
print(data['_id'])# only shows me the first '_id' value
Thanks for the help!
[{
"_id": "5436e3abbae478396759f0cf",
"name": "ISIC_0000000",
"updated": "2015-02-23T02:48:17.495000+00:00"
},
{
"_id": "5436e3acbae478396759f0d1",
"name": "ISIC_0000001",
"updated": "2015-02-23T02:48:27.455000+00:00"
},
{
"_id": "5436e3acbae478396759f0d3",
"name": "ISIC_0000002",
"updated": "2015-02-23T02:48:37.249000+00:00"
},
{
"_id": "5436e3acbae478396759f0d5",
"name": "ISIC_0000003",
"updated": "2015-02-23T02:48:46.021000+00:00"
}]
You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:
input_file = open('input_file.txt')
data = json.load(input_file) # get the data list
for element in data: # iterate on each element of the list
# element is a dict
id = element['_id'] # get the id
print(id) # print it
If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:
ids = [ e['_id'] for e in data ] # get id from each element and create a list of them
As you can see the data is a list of dictionaries
for looping over data you need to use the following code
for each in data:
print each['_id']
print each['name']
print each['updated']
it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
Yes, but you can loop over all the dictionaries in your list and get the values for their '_id' keys. This can be done in a single line using list comprehension:
data = json.load(input_file)
ids = [value['_id'] for value in data]
print(ids)
['5436e3abbae478396759f0cf', '5436e3acbae478396759f0d1', '5436e3acbae478396759f0d3', '5436e3acbae478396759f0d5']
Another way to achieve this is using the map built-in function of python:
ids = map(lambda value: value['_id'], data)
This creates a function that returns the value of the key _id from a dictionary using a lambda expression and then returns a list with the return value from this function applied on every item in data
Really can't get out of this...
Here's my python code:
for i in range(len(realjson)) :
store["Store"]={
"id" :realjson[i]['id'].strip(),
"retailer_id" :RETAILER_ID,
"name" :find(realjson[i]["title"],">","<").strip(),
"address" :realjson[i]["address"].strip(),
"city" :realjson[i]["address"].split(",")[-4].strip(),
"province" :realjson[i]["address"].split(",")[-3].strip(),
"group" :realjson[i]["address"].split(",")[-1].strip(),
"zip" :realjson[i]["address"].split(",")[-2].strip(),
"url" :"http://blabla.com?id="+realjson[i]["id"].strip(),
"lat" :realjson[i]["lat"].strip(),
"lng" :realjson[i]["lon"].strip(),
"phone" :realjson[i]["telephone_number"].replace("<br />Phone Number: ","").strip()
}
stores.append(store)
print stores[i]
When I print the list inside the for loop it works correctly.
Otherwise when I print the array outside the loop like this:
print storesit contains only the last element that I've appended repeated for the entire length of the list.
Do you have some advice to help me!
Thank you.
You reuse a mutable object in your loop:
store['Store']
Create a new copy in the loop instead:
newstore = store.copy()
newstore['Store'] = { ... }
store["Store"]={ ... }
if you expect this line to create new dictionary with just one key, then what you actually want is
store = {"Store": { ... }}