I'm trying to build a function that checks and returns an entry that matches its records.
Only issue is that there are 2 values (album_title and songs) in the dictionaries and I don't know how to loop through the 2nd value.
def make_album(artist, album_title, songs = None):
A = {
'artist1': 'album1', 'songs': '1'
}
B = {
'artist2': 'album2', 'songs': '2'
}
C = {
'artist3': 'album3', 'songs': '3'
}
dicts = [A, B, C]
for dictionary in dicts:
for key, value in dictionary.items():
if key == artist and value == album_title:
print(dictionary)
make_album('artist2', 'album2')
Any help is appreciated.
Thanks!
Seems like each dict here is really a pseudo-object describing describing an album. You don't want to iterate it at all, just perform lookups as needed.
So instead of:
for key, value in dictionary.items():
if key == artist and value == album_title:
print(dictionary)
you'd want something like:
if dictionary.get(artist, None) == album_title:
print(dictionary)
or roughly equivalently:
if artist in dictionary and dictionary[artist] == album_title:
print(dictionary)
Both of those do the same basic thing:
Check if the provided artist is a key in the dict, and
Verify that the album title associated with it matches the provided album_title
If both checks pass, you've found the album you were looking for. No need to loop at all, you just use the cheap membership tests and lookup-by-key features of dict to check the specific data you're interested in.
Once you know you've got a hit, you can just look up dictionary['songs'] to get the value associated with that key.
Related
Basically I am trying to find a way to get the key of a value from a dictionary by searching the value.
people = {
"Sarah" : "36",
"David" : "42",
"Ricky" : "13"
}
user_input = ('Enter the age of the individual") #The user enters the
#value
key_to_output = (...) #The variable that would contain the key value
print(key_to_output)
For example in the dictionary above if the user enters "36", they would be returned have "Sarah" returned. The dictionary I am using will never have a overlapping values so don't worry about any issues that would cause.
Also, because my python knowledge isn't very advanced it would be much appreciated if the responses were kept quite amateur so I can understand them properly.
You can invert the dictionary as so -
people_inv = {v:k for k,v in people.items()}
Now say your user inputted 36,
user_input = "36"
people_inv[user_input] # this will give Sarah
If the values are not unique like in the example below, you can do this -
people = {"Sarah":36, "Ricky":36, "Pankaj":28}
people_inv= {}
for k,v in people.items():
people_inv.setdefault(v, []).append(k)
people_inv["36"]
Output
['Sarah', 'Ricky']
The easyest way would be to itterate over the values like this.
def find_key(value, people):
for name in people:
if people[name] == value:
return name
If you are trying to get mutliple keys I would try:
def find_key(value, people):
names = []
for name in people:
if people[name] == value:
names.append(name)
return names
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:
all('site' in site for site in summary)
Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?
Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.
[
{"site": "site_A"},
{"site": "site_B"},
{"site": "site_C", "cost": 1000}
]
If all dictionaries have the key site, the dictionaries have a length of at least 1. The presence of any other key would increase the dictionary size to be greater than 1, test for that:
any(len(d) > 1 for d in summary)
You could just check, for each dictionary dct:
any(key != "site" for key in dct)
If you want to check this for a list of dictionaries dcts, shove another any around that: any(any(key != "site" for key in dct) for dct in dcts)
This also makes it easily extensible to allowing multiple different keys. (E.g. any(key not in ("site", "otherkey") for key in dct)) Because what's a dictionary good for if you can only use one key?
This is a bit longer version, but it gives you what you need. Just to give more options:
any({k: v for k, v in site.items() if k != 'site'} for site in summary)
I've got a dictionary like the one, below:
{ "amplifier": ["t_audio"],
"airbag": ["t_trigger"],
"trigger": ["t_sensor1", "t_sensor2"],
"hu": ["t_fused"],
"cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"],
"video_screen": ["t_video"] }
as you can see, there are some elements which have more than one value assigned for each key. I'd like to extract those values as string, separately within (preferably) a for loop then print them out. Printed result should be something like this:
group(amplifier, t_audio)
group(airbag, t_trigger)
group(trigger, t_sensor1)
group(trigger, t_sensor2)
group(hu, t_fused)
group(cam, t_front)
group(cam, t_ldw)
...
...
I can easily perform this on a normal dictionary where each key has only one values but got almost confused about this one(sorry if I'm newbe to Python...). Any kind of help is appreciated on how to get this result.
Very simple: loop through each key in the dictionary. Since each value is going to be a list with one or more elements, just loop through those and print the string you need:
d = {'amplifier': ['t_audio'], 'hu': ['t_fused'], 'trigger': ['t_sensor1', 't_sensor2'], 'cam': ['t_front', 't_ldw', 't_left', 't_nivi', 't_rear_camera', 't_right'], 'airbag': ['t_trigger'], 'video_screen': ['t_video']}
for key in d:
for value in d[key]:
print 'group({},{})'.format(key,value)
You can see it in action here: https://eval.in/645071
for key in dict:
for value in dict[key]:
print value
for k, v in mydict.iteritems():
for vv in v:
print "group(%s,%s)" % (k,vv)
#or
print "group(",k,",",vv,")"
#or the python 3 format syntax
In the below Python Code, am dynamically create Lists.
g['quest_{0}'.format(random(x))] = []
where random(x) is a random number, how to print the List(get the name of the dynamically created List name?)
To get a list of all the keys of your dictionary :
list(g.keys())
There is nothing different with a regular dictionary because you generate the key dynamically.
Note that you can also put any type of hashable object as a key, such as a tuple :
g[('quest', random(x))] = []
Which will let you get a list of all your quest numbers easily :
[number for tag, number in g.keys() if tag == "quest"]
With this technic, you can actually loop through the tag ('quest'), the number and the value in one loop :
for (tag, number), value in g.items():
# do somthing
Unpacking is your best friend in Python.
You can iterate over the g dictionary with a for loop, like this
for key, value in g.items():
print key, value
This will print all the keys and their corresponding lists.
I have a dictionary and I would like to get some values from it based on some keys. For example, I have a dictionary for users with their first name, last name, username, address, age and so on. Let's say, I only want to get one value (name) - either last name or first name or username but in descending priority like shown below:
(1) last name: if key exists, get value and stop checking. If not, move to next key.
(2) first name: if key exists, get value and stop checking. If not, move to next key.
(3) username: if key exists, get value or return null/empty
#my dict looks something like this
myDict = {'age': ['value'], 'address': ['value1, value2'],
'firstName': ['value'], 'lastName': ['']}
#List of keys I want to check in descending priority: lastName > firstName > userName
keySet = ['lastName', 'firstName', 'userName']
What I tried doing is to get all the possible values and put them into a list so I can retrieve the first element in the list. Obviously it didn't work out.
tempList = []
for key in keys:
get_value = myDict.get(key)
tempList .append(get_value)
Is there a better way to do this without using if else block?
One option if the number of keys is small is to use chained gets:
value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))
But if you have keySet defined, this might be clearer:
value = None
for key in keySet:
if key in myDict:
value = myDict[key]
break
The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that the extra lookups matter, use the for loop.
Use .get(), which if the key is not found, returns None.
for i in keySet:
temp = myDict.get(i)
if temp is not None:
print temp
break
You can use myDict.has_key(keyname) as well to validate if the key exists.
Edit based on the comments -
This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1
If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):
def getAny(dic, keys, default=None):
return (keys or default) and dic.get(keys[0],
getAny( dic, keys[1:], default=default))
or even better, without recursion and more clear:
def getAny(dic, keys, default=None):
for k in keys:
if k in dic:
return dic[k]
return default
Then that could be used in a way similar to the dict.get method, like:
getAny(myDict, keySet)
and even have a default result in case of no keys found at all:
getAny(myDict, keySet, "not found")