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.
Related
I'm watching a python course and I saw a line of code that I don't understand
books_dict[title] = [author,subject,year]
what I see from this line is the key of books_dict is the title and there are multiple values for it?
You can print the type of books_dict[title] with type() function. It tells you that it's a list(so there is only one object). List is a container so it can contain other objects. In your dictionary there is only one value for that key. Whenever you access to that key you will get that one list not individual items inside it. That would be problematic then!
If you have:
d = {}
d["key1"] = [1, 2, 3]
There is only one value, and that value is a list. The list is [author, subject, year].
In addition to what others have already stated, a dictionary holds key, value pairs. One key to one value, however the data types used to create the key and value can both be containers holding more than one element
for example
books_dict[title] = [author,subject,year]
is the same as
temp = [author, subject, year]
books_dict[title] = temp
The key can also hold an iterable, however it must be hashable and immutable.
books_dict[(title, author)] = [subject, year]
which is the same as
key = (title, author)
value = [subject, year]
books_dict[key] = value
I am trying to find a way to remove duplicates from a dict list. I don't have to test the entire object contents because the "name" value in a given object is enough to identify duplication (i.e., duplicate name = duplicate object). My current attempt is this;
newResultArray = []
for i in range(0, len(resultArray)):
for j in range(0, len(resultArray)):
if(i != j):
keyI = resultArray[i]['name']
keyJ = resultArray[j]['name']
if(keyI != keyJ):
newResultArray.append(resultArray[i])
, which is wildly incorrect. Grateful for any suggestions. Thank you.
If name is unique, you should just use a dictionary to store your inner dictionaries, with name being the key. Then you won't even have the issue of duplicates, and you can remove from the list in O(1) time.
Since I don't have access to the code that populates resultArray, I'll simply show how you can convert it into a dictionary in linear time. Although the best option would be to use a dictionary instead of resultArray in the first place, if possible.
new_dictionary = {}
for item in resultArray:
new_dictionary[item['name']] = item
If you must have a list in the end, then you can convert back into a dictionary as such:
new_list = [v for k,v in new_dictionary.items()]
Since "name" provides uniqueness... and assuming "name" is a hashable object, you can build an intermediate dictionary keyed by "name". Any like-named dicts will simply overwrite their predecessor in the dict, giving you a list of unique dictionaries.
tmpDict = {result["name"]:result for result in resultArray}
newArray = list(tmpDict.values())
del tmpDict
You could shrink that down to
newArray = list({result["name"]:result for result in resultArray}.values())
which may be a bit obscure.
I have imported a json file and converted it to a python dict. From there I extracted the dict I needed and imported it into a list. Now I would like to manipulate the items further, for example only extract 'player_fullname' : 'Lenny Hampel'. However, it seems that there is another dict inside the list, which len is 1, and I cannot access it.
It is a list with 1 entry and the entry is the dict. Easiest way would be:
player = player[0] #get the dict
print(player['player_fullname'])
Check player_fullname whether in your dict and then compare name value.
[item for item in your_dict if item.get('player_fullname', '') == 'Lenny Hampel']
I have a dictionary with lists attached to the keys with multiple values inside each list. I'm trying to pull a specific item from the lists of each key. I assumed I could do the following;
for entries in myDictionary:
print("Customer :" + entries[1])
print("Sales Rep:" + entries[2])
print("Item: " + entries[3])
Though that only prints the second, third, and fourth characters of what I assume to be the key itself - it could also be the first list item as I also have the key as the first item within the lists, but I'm going to assume it's the former.
I've read about the following, but I'm unsure how to apply it to my case of wanting to print a specific item from the list. I believe these would print out the entire list per key;
for key, value in my_dict.iteritems():
print key, value
for key in my_dict.iterkeys():
print key
for value in my_dict.itervalues():
print value
Cheers.
Iterating over the dictionary gives you keys; you can always use that key to access the value:
for key in myDictionary:
entries = myDictionary[key]
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])
Using dict.values() (or dict.itervalues() or dict.viewvalues() when using Python 2) gives you access to the values instead, which you can then index:
for entries in myDictionary.values():
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])
or you can have both the keys and the values with dict.items() (dict.iteritems(), dict.viewitems()):
for key, entries in myDictionary.items():
print("Details for:", key)
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])
I have some Python dictionaries like this:
A = {id: {idnumber: condition},....
e.g.
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
I need to search if the dictionary has any idnumber == 11 and calculate something with the condition. But if in the entire dictionary doesn't have any idnumber == 11, I need to continue with the next dictionary.
This is my try:
for id, idnumber in A.iteritems():
if 11 in idnumber.keys():
calculate = ......
else:
break
You're close.
idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
calculate = some_function_of(idnumber[idnum])
break # if we find it we're done looking - leave the loop
# otherwise we continue to the next dictionary
else:
# this is the for loop's 'else' clause
# if we don't find it at all, we end up here
# because we never broke out of the loop
calculate = your_default_value
# or whatever you want to do if you don't find it
If you need to know how many 11s there are as keys in the inner dicts, you can:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
This works because a key can only be in each dict once so you just have to test if the key exits. in returns True or False which are equal to 1 and 0, so the sum is the number of occurences of idnum.
dpath to the rescue.
http://github.com/akesterson/dpath-python
dpath lets you search by globs, which will get you what you want.
$ easy_install dpath
>>> for (path, value) in dpath.util.search(MY_DICT, '*/11', yielded=True):
>>> ... # 'value' will contain your condition; now do something with it.
It will iterate out all of the conditions in the dictionary, so no special looping constructs required.
See also
how do i traverse nested dictionaries (python)?
How to do this - python dictionary traverse and search
Access nested dictionary items via a list of keys?
Find all occurrences of a key in nested python dictionaries and lists
Traverse a nested dictionary and get the path in Python?
Find all the keys and keys of the keys in a nested dictionary
Searching for keys in a nested dictionary
Python: Updating a value in a deeply nested dictionary
Is there a query language for JSON?
Chained, nested dict() get calls in python