I have difficulties to generate a dictionary that contains identical keys. The actual code:
source = []
key = []
for foto in fotos.split(','):
source.append(str(foto))
key.append("source")
dictA = dict(zip(key, source))
pprint(dictA)
The output:
{'source': 'https://www.example.com/fma600/9364f794ed4e5cfc3ba9416ef4ebe065.jpg'}
But I need this dict output:
"pictures":[
{"source":"http://yourServer/path/to/your/picture.jpg"},
{"source":"http://yourServer/path/to/your/otherPicture.gif"},
{"source":"http://yourServer/path/to/your/anotherPicture.png"}
]
The problem is: the API needs to duplicate pictures using the same key "source". When I use dict, its not possible to duplicate and create another key with the same name.
You must use a list containing dict.
Reference URL: In Python, when to use a Dictionary, List or Set?
Please see following code.
dictA = []
for foto in fotos.split(','):
dictA.append({
'source':str(foto),
})
print(dictA)
For this specific case, unfortunatly python does not accept duplicate keys for dictionaries.. A possible workaround for the given problem, is to instead using dictionary, try using lists.
For example: listA = list(zip(key, source))
So the output should be something like:
"pictures":[
["source", "http://yourServer/path/to/your/picture.jpg"],
["source", "http://yourServer/path/to/your/otherPicture.gif"],
["source", "http://yourServer/path/to/your/anotherPicture.png"]
]
Those strings could be easily accessed by using the index [0] for the source string, and [1] for the link string.
Related
I need to select specific columns from a python dictionary using json.dumps().
Eg.
dict={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r=json.dumps(Only want "Bike":Yamaha","Car":"Jaguar")
Note: Cannot store the same into other dictionary and use it. As I want to use First K,V pair as well in my code.
Create a new dictionary and dump that.
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r = json.dumps({"Bike": d["Bike"], "Car": d["Car"]})
If you have a list of all the keys you want to keep, you can use a dictionary comprehension:
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
keep = ['Bike', 'Car']
r = json.dumps({key, d[key] for key in keep})
If you have a list of the keys you want to omit, you can also use a dictionary comprehension
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
skip = ['Greet']
r = json.dumps({key, val for key, val in d.items() if key not in skip})
BTW, don't use dict as a variable name, it's already the name of a built-in function/class.
final = list(mydict.items())[1:] #extra key:value tuple list slice of the portion you need
r=json.dumps(dict(final)) #cast to dictionary and dump
Output
{"Bike": "Yamaha", "Car": "Jaguar"}
I am trying to build a dictionary based on a larger input of text. From this input, I will create nested dictionaries which will need to be updated as the program runs. The structure ideally looks like this:
nodes = {}
node_name: {
inc_name: inc_capacity,
inc_name: inc_capacity,
inc_name: inc_capacity,
}
Because of the nature of this input, I would like to use variables to dynamically create dictionary keys (or access them if they already exist). But I get KeyError if the key doesn't already exist. I assume I could do a try/except, but was wondering if there was a 'cleaner' way to do this in python. The next best solution I found is illustrated below:
test_dict = {}
inc_color = 'light blue'
inc_cap = 2
test_dict[f'{inc_color}'] = inc_cap
# test_dict returns >>> {'light blue': 2}
Try this code, for Large Scale input. For example file input
Lemme give you an example for what I am aiming for, and I think, this what you want.
File.txt
Person1: 115.5
Person2: 128.87
Person3: 827.43
Person4:'18.9
Numerical Validation Function
def is_number(a):
try:
float (a)
except ValueError:
return False
else:
return True
Code for dictionary File.txt
adict = {}
with open("File.txt") as data:
adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip(' \n') for line in data.readlines() if is_number(line[line.index(':')+1: ].strip('\n')) == True}
print(adict)
Output
{'Person1': '115.5', 'Person2': '128.87', 'Person3': '827.43'}
For more explanation, please follow this issue solution How to fix the errors in my code for making a dictionary from a file
As already mentioned in the comments sections, you can use setdefault.
Here's how I will implement it.
Assume I want to add values to dict : node_name and I have the keys and values in two lists. Keys are in inc_names and values are in inc_ccity. Then I will use the below code to load them. Note that inc_name2 key exists twice in the key list. So the second occurrence of it will be ignored from entry into the dictionary.
node_name = {}
inc_names = ['inc_name1','inc_name2','inc_name3','inc_name2']
inc_ccity = ['inc_capacity1','inc_capacity2','inc_capacity3','inc_capacity4']
for i,names in enumerate(inc_names):
node = node_name.setdefault(names, inc_ccity[i])
if node != inc_ccity[i]:
print ('Key=',names,'already exists with value',node, '. New value=', inc_ccity[i], 'skipped')
print ('\nThe final list of values in the dict node_name are :')
print (node_name)
The output of this will be:
Key= inc_name2 already exists with value inc_capacity2 . New value= inc_capacity4 skipped
The final list of values in the dict node_name are :
{'inc_name1': 'inc_capacity1', 'inc_name2': 'inc_capacity2', 'inc_name3': 'inc_capacity3'}
This way you can add values into a dictionary using variables.
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 for loop that goes through two lists and combines them in dictionary. Keys are strings (web page headers) and values are lists (containing links).
Sometimes I get the same key from the loop that already exists in the dictionary. Which is fine. But the value is different (new links) and I'd like to update the key's value in a way where I append the links instead of replacing them.
The code looks something like that below. Note: issue_links is a list of URLs
for index, link in enumerate(issue_links):
issue_soup = BeautifulSoup(urllib2.urlopen(link))
image_list = []
for image in issue_soup.findAll('div', 'mags_thumb_article'):
issue_name = issue_soup.findAll('h1','top')[0].text
image_list.append(the_url + image.a['href'])
download_list[issue_name] = image_list
Currently the new links (image_list) that belong to the same issue_name key get overwritten. I'd like instead to append them. Someone told me to use collections.defaultdict module but I'm not familiar with it.
Note: I'm using enumerate because the index gets printed to the console (not included in the code).
Something like this:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
d["b"].append(3)
Then:
print(d)
defaultdict(<class 'list'>, {'b': [3], 'a': [1, 2]})
if download_list.has_key(issume_name):
download_list[issume_name].append(image_list)
else:
download_list[issume_name] = [image_list]
is it right?If you have the same key, append the list.
I am attempting to generate a URL link in the following format using urllib and urlencode.
<img src=page.psp?KEY=%28SpecA%2CSpecB%29&VALUE=1&KEY=%28SpecA%2C%28SpecB%2CSpecC%29%29&VALUE=2>
I'm trying to use data from my dictionary to input into the urllib.urlencode() function however, I need to get it into a format where the keys and values have a variable name, like below. So the keys from my dictionary will = NODE and values will = VALUE.
wanted = urllib.urlencode( [("KEY",v1),("VALUE",v2)] )
req.write( "<a href=page.psp?%s>" % (s) );
The problem I am having is that I want the URL as above and instead I am getting what is below, rather than KEY=(SpecA,SpecB) NODE=1, KEY=(SpecA,SpecB,SpecC) NODE=2 which is what I want.
KEY=%28SpecA%2CSpecB%29%2C%28%28SpecA%2CSpecB%29%2CSpecC%29&VALUE=1%2C2
So far I have extracted keys and values from the dictionary, extracted into tuples, lists, strings and also tried dict.items() but it hasn't helped much as I still can't get it to go into the format I want. Also I am doing this using Python server pages which is why I keep having to print things as a string due to constant string errors. This is part of what I have so far:
k = (str(dict))
ver1 = dict.keys()
ver2 = dict.values()
new = urllib.urlencode(function)
f = urllib.urlopen("page.psp?%s" % new)
I am wondering what I need to change in terms of extracting values from the dictionary/converting them to different formats in order to get the output I want? Any help would be appreciated and I can add more of my code (as messy as it has become) if need be. Thanks.
This should give you the format you want:
data = {
'(SpecA,SpecB)': 1,
'(SpecA,SpecB,SpecC)': 2,
}
params = []
for k,v in data.iteritems():
params.append(('KEY', k))
params.append(('VALUE', v))
new = urllib.urlencode(params)
Note that the KEY/VALUE pairings may not be the order you want, given that dicts are unordered.