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}
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 want to create a dictionary with Key value pairs which are filled via an for Loop
The dictionary I want to achive
[
{
"timestamp": 123123123,
"image": "image/test1.png"
},
{
"timestamp": 0384030434,
"image": "image/test2.png"
}
]
My code does not work and I´m new to the datatypes of python.
images_dict = []
for i in images:
time = Image.open(i)._getexif()[36867]
images_dict = {"timestamp": time, "image": i}
What am I missing?
First, you seem to be confusing the definition of a list and a dictionary in python. Dictionaries use curly brackets {} and lists use regular brackets []. So in your first example, you are describing a list with a single element, which is a dictionary.
As for your code example, you are creating an empty list, and then iterating over images which I assume is a list of images, and then redefining the variable images_dict to be a dictionary with two key: value pairs for every iteration.
It seems like what you want is this:
images_dict = []
for image in images:
time = Image.open(1)._getexif()[36867]
images_dict.append({'timestamp': time, 'image': image})
The answer from Tom McLean worked for me, I´m a little bit confused with the dataypes of python
images_dict.append({"timestamp": time, "image": i})
I have the JSON which looks like this:-
{
"name": "PT",
"batservers": [
{"name": "bat1", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat2", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat3", "qmchannel": "abcd", "mount": "efgh"},
]
}
I want to retrieve the value of "name" present in all the dictionary and save it in a list variable i.e. ["bat1","bat2","bat3"]
I tried something like this:-
batsList = env["batservers"][0:]["name"]
but it displays the below error:-
TypeError: list indices must be integers or slices, not str
I know I can do this using a loop but can someone please help me to do using in a single line code way which I am trying above?
Thanks,
SUYASH GUPTA.
You can't do it without a loop. But the loop can be a list comprehension:
batsList = [b['name'] for b in env["batservers"]
How about saving the list as:
list_of_names = [x[name] for x in env["batservers"]]
Try this:
[b['name'] for b in env['batservers']]
Or this:
map(lambda b: b['name'], env['batservers'])
[0:] doesn't do much for you: it returns the same array of dictionaries.
env["batservers"][0:] returns a list, and you can't access directly the values of the dicts in the list.
You can use a list comprehension:
names = [elem["name"] for elem in env["batservers"]]
This is a basic solution using a for loop to iterate over the sub dictionary and appending to the empty list res.
res = []
for item in env["batservers"]:
res.append(item["name"])
print (res) #=> ['bat1', 'bat2', 'bat3']
I am parsing some information from a CSV File and am inputting it into a dict of dicts. The inner dict v contains the following elements {'140725AD4': <mod.City object at 1x3259C2D1>, '631315AD2': <mod.City object at 0x023A4870>}. How would I access the object <mod.city object at 0x0138C3B0> for example?
Thank You.
Having a structure like the following:
john = {
"name": "John",
"family": {
"son": "Ret",
"daughter": "Pat"
}
}
You can access the John son's name like this:
john['family']['son']
This will return "Ret"
In your case, if City object is a DICT you can use:
dict['140725AD4']['population']
If your City object is just a Class you can do
dict['140725AD4'].getPopulation()
or
dict['140725AD4'].population
How it works?
A dictionary is a hashmap of pairs (name, value). Whenever you call a name the value is given. In Python, the value can be anything, from int to a Class.
So when in a dict you ask for a name inside a dict like dict['name'] you get back the value associated with it. In this case its your City object. Then you can call anything related to the value: functions, variables...
Assuming this question is the follow up for this one - Updating Dictionary of Dictionaries in Python you would have to do this:
inner_dict = places["City"]
for _, city_obj in inner_dict.items():
print city_obj.population # Assuming population is one of the member variables of the class mod.city
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)}